Class: ConfigReader::MagicHash

Inherits:
Hash
  • Object
show all
Defined in:
lib/config_reader/magic_hash.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(key, *args, &block) ⇒ Object



28
29
30
31
32
33
34
35
36
# File 'lib/config_reader/magic_hash.rb', line 28

def method_missing(key, *args, &block)
  begin
    has_key?(key) ?
      fetch(key) :
      super
  rescue KeyError, NoMethodError => e
    raise e unless ignore_missing_keys
  end
end

Instance Attribute Details

#ignore_missing_keysObject

Returns the value of attribute ignore_missing_keys.



3
4
5
# File 'lib/config_reader/magic_hash.rb', line 3

def ignore_missing_keys
  @ignore_missing_keys
end

Class Method Details

.convert_hash(hash, ignore_missing_keys = false) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
18
# File 'lib/config_reader/magic_hash.rb', line 5

def self.convert_hash(hash, ignore_missing_keys=false)
  magic_hash = new
  magic_hash.ignore_missing_keys = ignore_missing_keys

  hash.each_pair do |key, value|
    if value.is_a?(Hash)
      magic_hash[key.to_sym] = convert_hash(value, ignore_missing_keys)
    else
      magic_hash[key.to_sym] = value
    end
  end

  magic_hash
end

Instance Method Details

#[](key) ⇒ Object



20
21
22
23
24
25
26
# File 'lib/config_reader/magic_hash.rb', line 20

def [](key)
  begin
    fetch(key.to_sym)
  rescue KeyError => e
    raise e unless ignore_missing_keys
  end
end