Class: EasyHtmlGenerator::Config::ConfigHash

Inherits:
Hash
  • Object
show all
Defined in:
lib/easy_html_generator/config.rb

Overview

symbolizes the keys and makes the hash accessable via object attributes

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(hash = nil) ⇒ ConfigHash

Returns a new instance of ConfigHash.



15
16
17
18
19
20
21
22
# File 'lib/easy_html_generator/config.rb', line 15

def initialize(hash = nil)
  super

  return unless hash

  hash = self.class.symbolize_keys hash
  hash.each { |k, v| self[k] = v }
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
# File 'lib/easy_html_generator/config.rb', line 24

def method_missing(name, *args)
  # setter
  if /^(\w+)=$/ =~ name
    self[Regexp.last_match(1).to_sym] = args[0]
  # getter
  else
    return super.method_missing name unless key? name
  end

  self[name]
end

Class Method Details

.symbolize_keys(obj) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/easy_html_generator/config.rb', line 36

def self.symbolize_keys(obj)
  case obj
  when Array
    obj.inject([]) do |res, val|
      res << case val
             when Hash, Array
               symbolize_keys(val)
             else
               val
        end
      res
    end
  when Hash
    obj.inject(ConfigHash.new) do |res, (key, val)|
      nkey = case key
             when String
               key.to_sym
             else
               key
        end
      nval = case val
             when Hash, Array
               symbolize_keys(val)
             else
               val
        end
      res[nkey] = nval
      res
    end
  else
    obj
  end
end