Module: Configurable::Conversions

Includes:
ConfigTypes
Defined in:
lib/configurable/conversions.rb

Overview

A set of methods used to convert various inputs based on a hash of (key, Config) pairs. Extend the hash and then use the methods.

Instance Method Summary collapse

Instance Method Details

#export(source, target = {}) ⇒ Object



64
65
66
67
68
69
70
71
72
73
74
# File 'lib/configurable/conversions.rb', line 64

def export(source, target={})
  each_value do |config|
    key = config.key
    
    if source.has_key?(key)
      target[config.name] = config.uncast(source[key])
    end
  end
  
  target
end

#import(source, target = {}) ⇒ Object



52
53
54
55
56
57
58
59
60
61
62
# File 'lib/configurable/conversions.rb', line 52

def import(source, target={})
  each_value do |config|
    name = config.name
    
    if source.has_key?(name)
      target[config.key] = config.cast(source[name])
    end
  end
  
  target
end

#to_defaultObject

Returns a hash of the default values for each config in self.



44
45
46
47
48
49
50
# File 'lib/configurable/conversions.rb', line 44

def to_default
  default = {}
  each_pair do |key, config|
    default[key] = config.default
  end
  default
end

#to_parser(*args, &block) ⇒ Object

Initializes and returns a ConfigParser generated using the configs for self. Arguments given to parser are passed to the ConfigParser initializer.



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/configurable/conversions.rb', line 14

def to_parser(*args, &block)
  parser = ConfigParser.new(*args, &block)
  traverse do |nesting, config|
    next if config[:hidden] == true || nesting.any? {|nest| nest[:hidden] == true }
    
    nest_keys   = nesting.collect {|nest| nest.key }
    long, short = nesting.collect {|nest| nest.name }.push(config.name).join(':'), nil
    long, short = short, long if long.length == 1
    
    guess_attrs = {
      :long => long,
      :short => short
    }
    
    config_attrs = {
      :key       => config.key, 
      :nest_keys => nest_keys,
      :default   => config.default,
      :callback  => lambda {|value| config.type.cast(value) }
    }
    
    attrs = guess_attrs.merge(config.).merge(config_attrs)
    parser.on(attrs)
  end
  
  parser.sort_opts!
  parser
end

#traverse(nesting = [], &block) ⇒ Object

Yields each config in configs to the block with nesting, after appened self to nesting.



78
79
80
81
82
83
84
85
86
87
88
89
# File 'lib/configurable/conversions.rb', line 78

def traverse(nesting=[], &block)
  each_value do |config|
    if config.type.kind_of?(NestType)
      nesting.push config
      configs = config.type.configurable.class.configs
      configs.traverse(nesting, &block)
      nesting.pop
    else
      yield(nesting, config)
    end
  end
end