Class: HashBuilder
- Inherits:
-
Object
- Object
- HashBuilder
- Defined in:
- lib/hash_builder.rb
Overview
This class simplifies the creation of potentially deeply nested hashes It turns code like this:
hash = {
one: {
two: {
three: {
four: :foo
}
}
}
}
Into this:
hash = HashBuilder.new
hash.one.two.three.four = :foo
The underlaying hash can be retrieved with #as_json.
NOTE: Its good practice to also implement respond_to_missing? when overriding method_missing, but for some reason that makes the tests fail.
Instance Method Summary collapse
- #as_json ⇒ Object
-
#initialize ⇒ HashBuilder
constructor
A new instance of HashBuilder.
- #method_missing(name, *args) ⇒ Object
Constructor Details
#initialize ⇒ HashBuilder
Returns a new instance of HashBuilder.
24 25 26 |
# File 'lib/hash_builder.rb', line 24 def initialize @hash = {} end |
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(name, *args) ⇒ Object
32 33 34 35 36 37 38 39 40 41 |
# File 'lib/hash_builder.rb', line 32 def method_missing(name, *args) match = name.to_s.match(/(?<key>.*?)=$/) if match.present? @hash[match[:key].to_sym] = args.first else @hash[name] = HashBuilder.new if @hash[name].blank? @hash[name] end end |
Instance Method Details
#as_json ⇒ Object
28 29 30 |
# File 'lib/hash_builder.rb', line 28 def as_json @hash.as_json end |