Class: Babushka::LambdaChooser

Inherits:
Object
  • Object
show all
Defined in:
lib/babushka/lambda_chooser.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(owner, *possible_choices, &block) ⇒ LambdaChooser

Returns a new instance of LambdaChooser.

Raises:

  • (ArgumentError)

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

#ownerObject (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
  metaclass.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