Class: Babushka::LambdaChooser
Instance Attribute Summary collapse
-
#owner ⇒ Object
readonly
Returns the value of attribute owner.
Instance Method Summary collapse
- #choose(choices, method_name = nil) ⇒ Object
-
#initialize(owner, *possible_choices, &block) ⇒ LambdaChooser
constructor
A new instance of LambdaChooser.
- #on(choices, first = nil, *rest, &block) ⇒ Object
- #otherwise(first = nil, *rest, &block) ⇒ Object
- #var(name, opts = {}) ⇒ Object
Constructor Details
#initialize(owner, *possible_choices, &block) ⇒ LambdaChooser
Returns a new instance of LambdaChooser.
7 8 9 10 11 12 13 |
# File 'lib/babushka/lambda_chooser.rb', line 7 def initialize owner, *possible_choices, &block raise ArgumentError, "You can't use :otherwise as a choice name, because it's reserved." if possible_choices.include?(:otherwise) @owner = owner @possible_choices = possible_choices.push(:otherwise) @block = block @results = {} end |
Instance Attribute Details
#owner ⇒ Object (readonly)
Returns the value of attribute owner.
3 4 5 |
# File 'lib/babushka/lambda_chooser.rb', line 3 def owner @owner end |
Instance Method Details
#choose(choices, method_name = nil) ⇒ Object
15 16 17 18 19 |
# File 'lib/babushka/lambda_chooser.rb', line 15 def choose choices, method_name = nil .send :alias_method, method_name, :on unless method_name.nil? block_result = instance_eval(&@block) @results.empty? ? block_result : [choices].flatten(1).push(:otherwise).pick {|c| @results[c] } end |
#on(choices, first = nil, *rest, &block) ⇒ Object
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
# File 'lib/babushka/lambda_chooser.rb', line 25 def on choices, first = nil, *rest, &block raise "You can supply values or a block, but not both." if first && block [choices].flatten(1).each {|choice| raise "The choice '#{choice}' isn't valid." unless @possible_choices.include?(choice) @results[choice] = if block block elsif first.is_a? Hash first else [first].flatten(1).concat(rest) end } end |
#otherwise(first = nil, *rest, &block) ⇒ Object
21 22 23 |
# File 'lib/babushka/lambda_chooser.rb', line 21 def otherwise first = nil, *rest, &block on :otherwise, first, *rest, &block end |
#var(name, opts = {}) ⇒ Object
5 |
# File 'lib/babushka/lambda_chooser.rb', line 5 def var(name, opts = {}) owner.var(name, opts) end |