Class: SwitchBlock::BlockSwitcher

Inherits:
BlankSlate
  • Object
show all
Defined in:
lib/rails/multi_block_helpers/switch_block.rb

Instance Method Summary collapse

Constructor Details

#initialize(x, args) ⇒ BlockSwitcher

Returns a new instance of BlockSwitcher.



14
15
16
17
18
19
20
# File 'lib/rails/multi_block_helpers/switch_block.rb', line 14

def initialize(x, args)
  @x = x
  @args = args
  @ret = nil
  @called = false
  @callees = []
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args, &block) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/rails/multi_block_helpers/switch_block.rb', line 26

def method_missing(method, *args, &block)
  if (method.downcase == @x.to_sym.downcase or method == :always) or (@called == false and method == :else) then
    @called = true
    if args.size > 0 then
      @ret = args.first.call(*@args)
    else
      @ret = block.call(*@args)
    end
  end
  # For error reporting
  @callees << method
  @callees.uniq!
  # Always return something meaningful
  @ret
end

Instance Method Details

#ensureObject



22
23
24
# File 'lib/rails/multi_block_helpers/switch_block.rb', line 22

def ensure
  raise NothingExecutedError, "Nothing got executed! Expected one of #{@callees.inspect}, but only got #{@x}" if not @called
end