Class: Confection::HashBuilder
- Inherits:
- BasicObject
- Defined in:
- lib/confection/hash_builder.rb
Overview
HashBuilder takes a procedure and builds a Hash out of it.
The procedure must conform to a set of rules to be useful in this respect. They must either take an argument and use that argument to set values, or if no argument is taken then ‘#instance_eval` is used to evaluate the procedure such that each method represents a key.
Instance Method Summary collapse
-
#initialize(hash = {}, &block) ⇒ HashBuilder
constructor
A new instance of HashBuilder.
- #method_missing(s, *a, &b) ⇒ Object
- #to_h ⇒ Object
Constructor Details
#initialize(hash = {}, &block) ⇒ HashBuilder
Returns a new instance of HashBuilder.
13 14 15 16 17 18 19 20 21 |
# File 'lib/confection/hash_builder.rb', line 13 def initialize(hash={}, &block) @hash = hash case block.arity when 0 instance_eval(&block) else block.call(self) end end |
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(s, *a, &b) ⇒ Object
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
# File 'lib/confection/hash_builder.rb', line 29 def method_missing(s, *a, &b) m = s.to_s if a.empty? && !b @hash[m.to_sym] else if b @hash[m.chomp('=').to_sym] = HashBuilder.new(&b).to_h else if a.size > 1 @hash[m.chomp('=').to_sym] = a else @hash[m.chomp('=').to_sym] = a.first end end end end |
Instance Method Details
#to_h ⇒ Object
24 25 26 |
# File 'lib/confection/hash_builder.rb', line 24 def to_h @hash end |