Module: Kase::Switcher::DSL

Defined in:
lib/kase/switcher.rb

Class Method Summary collapse

Class Method Details

.call(switcher, &block) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/kase/switcher.rb', line 45

def call(switcher, &block)
  context = eval("self", block.binding)
  original_on_method = context.method(:on) if defined? context.on
  new_on_method = nil

  # Define a new :on method for the caller context
  context.define_singleton_method(:on) do |*pattern, &inner_block|

    new_inner_block = proc do |*args|
      # Use the original :on method inside the inner blocks
      DSL.set_on_method(context, original_on_method)
      result = inner_block.call(*args)
      DSL.set_on_method(context, new_on_method)
      result
    end

    switcher.on(*pattern, &new_inner_block)
  end
  new_on_method = context.method(:on)

  block.call
ensure
  DSL.set_on_method(context, original_on_method)
end

.set_on_method(context, method) ⇒ Object



70
71
72
73
74
75
76
# File 'lib/kase/switcher.rb', line 70

def set_on_method(context, method)
  if method
    context.define_singleton_method(:on, method)
  else
    context.instance_eval { undef :on if defined? on }
  end
end