Class: HashCollector
Overview
A DSL class that allows options to be collected for a field definition using a block and/or a hash.
hash = { :colour => :red, :hue => 15 }
collector = HashCollector.new( hash ) do |hc|
hc.saturation = 17
hc.opacity = 0.43
hc.grooviness = 100
end
or like this (without the block parameter)
collector = HashCollector.new( hash ) do
saturation 17
opacity 0.43
grooviness = 100
end
either way, a call to collector.to_hash will result in
{ :hue=>15, :saturation=>17, :opacity=>0.43, :grooviness=>100, :colour=>:red }
and the following accessors will be added
collector.hue
collector.hue( some_value )
collector.hue = some_value
for hue, saturation, opacity, grooviness and colour.
Direct Known Subclasses
Instance Method Summary collapse
-
#collect(args = {}, &block) ⇒ Object
evaluate the block and collect options from args.
-
#initialize(hash = {}, &block) ⇒ HashCollector
constructor
Collect values from the hash and the block, using the collect method.
-
#to_hash ⇒ Object
return a hash of the collected elements.
Constructor Details
#initialize(hash = {}, &block) ⇒ HashCollector
Collect values from the hash and the block, using the collect method.
30 31 32 33 |
# File 'lib/qtext/hash_collector.rb', line 30 def initialize( hash = {}, &block ) @hash = hash || {} gather( &block ) end |
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(sym, *args) ⇒ Object (protected)
Originally from Jim Freeze’s article. Add the accessor methods if they don’t already exist, and if dsl_dynamic is in effect, which is the default. If dsl_static is in effect, the normal method_missing behaviour will be invoked.
111 112 113 114 115 116 117 118 |
# File 'lib/qtext/hash_collector.rb', line 111 def method_missing(sym, *args) if self.class.dynamic? self.class.dsl_accessor sym send( sym, *args ) else super end end |
Instance Method Details
#collect(args = {}, &block) ⇒ Object
evaluate the block and collect options from args. Even if it’s nil.
36 37 38 39 40 41 42 43 44 45 |
# File 'lib/qtext/hash_collector.rb', line 36 def collect( args = {}, &block ) @hash.merge!( args || {} ) unless block.nil? if block.arity == -1 instance_eval &block else yield self end end end |
#to_hash ⇒ Object
return a hash of the collected elements
48 49 50 |
# File 'lib/qtext/hash_collector.rb', line 48 def to_hash @hash end |