Class: Cheffish::MergedConfig

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/cheffish/merged_config.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*configs) ⇒ MergedConfig

Returns a new instance of MergedConfig.



3
4
5
6
# File 'lib/cheffish/merged_config.rb', line 3

def initialize(*configs)
  @configs = configs
  @merge_arrays = {}
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name) ⇒ Object



48
49
50
# File 'lib/cheffish/merged_config.rb', line 48

def method_missing(name)
  self[name]
end

Instance Attribute Details

#configsObject (readonly)

Returns the value of attribute configs.



10
11
12
# File 'lib/cheffish/merged_config.rb', line 10

def configs
  @configs
end

Instance Method Details

#[](name) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/cheffish/merged_config.rb', line 21

def [](name)
  if @merge_arrays[name]
    configs.select { |c| !c[name].nil? }.collect_concat { |c| c[name] }
  else
    result_configs = []
    configs.each do |config|
      value = config[name]
      if !value.nil?
        if value.respond_to?(:keys)
          result_configs << value
        elsif result_configs.size > 0
          return result_configs[0]
        else
          return value
        end
      end
    end
    if result_configs.size > 1
      MergedConfig.new(*result_configs)
    elsif result_configs.size == 1
      result_configs[0]
    else
      nil
    end
  end
end

#eachObject



70
71
72
73
74
75
76
# File 'lib/cheffish/merged_config.rb', line 70

def each
  keys.each do |key|
    if block_given?
      yield key, self[key]
    end
  end
end

#each_pair(&block) ⇒ Object



66
67
68
# File 'lib/cheffish/merged_config.rb', line 66

def each_pair(&block)
  each(&block)
end

#key?(name) ⇒ Boolean Also known as: has_key?

Returns:

  • (Boolean)


52
53
54
# File 'lib/cheffish/merged_config.rb', line 52

def key?(name)
  configs.any? { |config| config.has_key?(name) }
end

#keysObject



58
59
60
# File 'lib/cheffish/merged_config.rb', line 58

def keys
  configs.map { |c| c.keys }.flatten(1).uniq
end

#merge_arrays(*symbols) ⇒ Object



11
12
13
14
15
16
17
18
19
# File 'lib/cheffish/merged_config.rb', line 11

def merge_arrays(*symbols)
  if symbols.size > 0
    symbols.each do |symbol|
      @merge_arrays[symbol] = true
    end
  else
    @merge_arrays
  end
end

#to_hashObject



78
79
80
81
82
83
84
# File 'lib/cheffish/merged_config.rb', line 78

def to_hash
  result = {}
  each_pair do |key, value|
    result[key] = value
  end
  result
end

#valuesObject



62
63
64
# File 'lib/cheffish/merged_config.rb', line 62

def values
  keys.map { |key| self[key] }
end