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, bind) ⇒ WrappedMethod

Wrap a method with catch DSL and pass in config.



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

def initialize(method, config, bind)
  @method = method
  @config = config
  @callbacks = {}
  @response = {}
  bind(bind)
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.



26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/named_return/wrapped_method.rb', line 26

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.



42
43
44
# File 'lib/named_return/wrapped_method.rb', line 42

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

#nameObject

Get wrapped method name.



16
17
18
# File 'lib/named_return/wrapped_method.rb', line 16

def name
  @method.name
end

#on(label, &block) ⇒ Object

DSL to add nested catch statements.



21
22
23
# File 'lib/named_return/wrapped_method.rb', line 21

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