Class: NamedReturn::WrappedMethod

Inherits:
Object
  • Object
show all
Defined in:
lib/named_return/wrapped_method.rb

Overview

Wrapper to store the original method with a DSL to catch named returns.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(method, config) ⇒ WrappedMethod

Wrap a method with catch DSL and pass in config.



7
8
9
10
# File 'lib/named_return/wrapped_method.rb', line 7

def initialize(method, config)
  @method = method
  @config = config
end

Instance Attribute Details

#configObject (readonly)

Returns the value of attribute config.



4
5
6
# File 'lib/named_return/wrapped_method.rb', line 4

def config
  @config
end

Instance Method Details

#call(*args, &block) ⇒ Object

Call the wrapped method with catches inserted by the DSL.



30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/named_return/wrapped_method.rb', line 30

def call(*args, &block)
  return_pair = recursive_catch(@callbacks.to_a, *args, &block)
  label, value = @response.first
  value = return_pair unless label # important swizzle for no `on` blocks

  if value.is_a?(Array) && value.first == :return
    # NB in this case `label` will be wrong (nil or outermost `catch`),
    # so we return a value where first element is the "real" label :return
    # and the last element is the actual value returned
    handle_return(value.last)
  else
    @callbacks[label].call(value)
  end
end

#call_original(*args, &block) ⇒ Object

Call the wrapped method directly.



46
47
48
# File 'lib/named_return/wrapped_method.rb', line 46

def call_original(*args, &block)
  @method.call(*args, &block)
end

#nameObject

Get wrapped method name.



13
14
15
# File 'lib/named_return/wrapped_method.rb', line 13

def name
  @method.name
end

#on(label, &block) ⇒ Object

DSL to add nested catch statements.



18
19
20
# File 'lib/named_return/wrapped_method.rb', line 18

def on(label, &block)
  @callbacks[label] = block
end

#reset(bind) ⇒ Object

Prepare for next run.



23
24
25
26
27
# File 'lib/named_return/wrapped_method.rb', line 23

def reset(bind)
  @callbacks = {}
  @response = {}
  bind(bind)
end