Class: ChainableMethods::Link

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

Instance Method Summary collapse

Constructor Details

#initialize(object, context) ⇒ Link

Returns a new instance of Link.



27
28
29
30
# File 'lib/chainable_methods.rb', line 27

def initialize(object, context)
  @state   = object
  @context = context
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

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



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/chainable_methods.rb', line 37

def method_missing(method_name, *args, &block)
  if is_constant?(method_name)
    return ChainableMethods::Link.new( @state, ::Kernel.const_get(method_name) )
  end

  local_response   = @state.respond_to?(method_name)
  context_response = @context.respond_to?(method_name)

  # if the state itself has the means to respond, delegate to it
  # but if the context has the behavior, it has priority over the delegation
  new_state = if local_response && !context_response
                @state.send(method_name, *args, &block)
              else
                @context.send(method_name, *args.unshift(@state), &block)
              end

  ChainableMethods::Link.new( new_state, @context )
end

Instance Method Details

#chain(&block) ⇒ Object



32
33
34
35
# File 'lib/chainable_methods.rb', line 32

def chain(&block)
  new_state = block.call(@state)
  ChainableMethods::Link.new( new_state, @context )
end

#unwrapObject



56
57
58
# File 'lib/chainable_methods.rb', line 56

def unwrap
  @state
end