Class: ChainableMethods::Link

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(object, context) ⇒ Link

Returns a new instance of Link.



19
20
21
22
# File 'lib/chainable_methods.rb', line 19

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

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

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



29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/chainable_methods.rb', line 29

def method_missing(name, *args, &block)
  local_response   = state.respond_to?(name)
  context_response = context.respond_to?(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
  if local_response && !context_response
    ChainableMethods::Link.new( state.send(name, *args, &block), context)
  else
    ChainableMethods::Link.new( context.send(name, *([state] + args), &block), context )
  end
end

Instance Attribute Details

#contextObject (readonly)

Returns the value of attribute context.



17
18
19
# File 'lib/chainable_methods.rb', line 17

def context
  @context
end

#stateObject (readonly)

Returns the value of attribute state.



17
18
19
# File 'lib/chainable_methods.rb', line 17

def state
  @state
end

Instance Method Details

#chain(&block) ⇒ Object



24
25
26
27
# File 'lib/chainable_methods.rb', line 24

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

#unwrapObject



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

def unwrap
  @state
end