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

- (LambdaChooser) initialize(owner, *possible_choices, &block)

A new instance of LambdaChooser

Raises:

  • (ArgumentError)


8
9
10
11
12
13
14
# File 'lib/babushka/lambda_chooser.rb', line 8

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

- (Object) owner (readonly)

Returns the value of attribute owner



4
5
6
# File 'lib/babushka/lambda_chooser.rb', line 4

def owner
  @owner
end

Instance Method Details

- (Object) choose(choices, method_name = nil)



16
17
18
19
20
# File 'lib/babushka/lambda_chooser.rb', line 16

def choose choices, method_name = nil
  self.class.send :alias_method, (method_name || :on), :process_choice
  block_result = instance_eval(&@block)
  @results.empty? ? block_result : [*choices].push(:otherwise).pick {|c| @results[c] }
end

- (Object) otherwise(first = nil, *rest, &block)



22
23
24
# File 'lib/babushka/lambda_chooser.rb', line 22

def otherwise first = nil, *rest, &block
  process_choice :otherwise, first, *rest, &block
end

- (Object) process_choice(choice, first = nil, *rest, &block)



26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/babushka/lambda_chooser.rb', line 26

def process_choice choice, first = nil, *rest, &block
  raise "You can supply values or a block, but not both." if first && block
  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].concat(rest)
  end
end

- (Object) var(name, opts = {})



6
# File 'lib/babushka/lambda_chooser.rb', line 6

def var(name, opts = {}) owner.var(name, opts) end