Class: SugarfreeConfig::ConfigIterator

Inherits:
Object
  • Object
show all
Defined in:
lib/sugarfree-config/config.rb

Overview

Config Iterator. Given a configuration hash it can navigate trough the values using method calls that will be translated into hash keys and indexed

Instance Method Summary collapse

Constructor Details

#initialize(configuration, first_path_element) ⇒ ConfigIterator

Create a new iterator with a given configuration and the first element of the path to be iterated (first_path_element)



83
84
85
86
# File 'lib/sugarfree-config/config.rb', line 83

def initialize(configuration, first_path_element)
  @scoped_config = configuration
  @path_elements = [first_path_element.to_s]
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(symbol, *args) ⇒ Object

Here is the magic. When an unknown symbol is passed this symbol is set as the last path element of this iteration, and the iterator is then forced to make that movement



101
102
103
104
# File 'lib/sugarfree-config/config.rb', line 101

def method_missing(symbol, *args)
  @path_elements << symbol.to_s
  self.next
end

Instance Method Details

#nextObject

Iterate to the next element in the path

Algorithm:

  1. Get the last element of the key path

  2. Try to find it in the scoped config

  3. If not present raise an error

  4. If present and is a hash we are not in a config leaf, so the scoped config is reset to this new value and self is returned

  5. If present and is a value then return the value



117
118
119
120
121
122
123
124
125
126
# File 'lib/sugarfree-config/config.rb', line 117

def next
  if (value = @scoped_config[@path_elements.last]).nil?
    raise ConfigKeyException.new(@path_elements)
  elsif value.is_a?(Hash)
    @scoped_config = value
    self
  else
    value
  end
end

#to_hashObject

Returns the current scope as a hash. Usefull to get a Big hash of config that will be used later.



92
93
94
# File 'lib/sugarfree-config/config.rb', line 92

def to_hash
  @scoped_config
end