Class: SmartDelegator

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

Overview

This class delegates method calls to the given object. If the returned value is an instance of the original object, the smart delegator will return a new instance of itself with the original object.

This is in contrast to SimpleDelegator which will return the original object.

The chart below demonstrates the difference:

`mymessage` ->
   SimpleDelegator ->
     OriginalObject ->
       invokes `mymessage` returning self ->
         returns OriginalObject
`mymessage` ->
   SmartDelegator  ->
     OriginalObject ->
       invokes `mymessage` returning self ->
         returns SmartDelegator decorating OriginalObject

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(object) ⇒ SmartDelegator

Returns a new instance of SmartDelegator.



26
27
28
# File 'lib/smart_delegator.rb', line 26

def initialize(object)
  @object = object
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

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



38
39
40
41
42
43
44
45
# File 'lib/smart_delegator.rb', line 38

def method_missing(method, *args, &block)
  returned_object = object.public_send(method, *args, &block)
  if returned_object.class == object.class
    self.class.new(returned_object)
  else
    returned_object
  end
end

Instance Attribute Details

#objectObject (readonly)

Returns the value of attribute object.



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

def object
  @object
end

Instance Method Details

#inspectObject



34
35
36
# File 'lib/smart_delegator.rb', line 34

def inspect
  "SmartDelegator(#{object.inspect})"
end

#respond_to?(method, include_private = false) ⇒ Boolean

Returns:

  • (Boolean)


30
31
32
# File 'lib/smart_delegator.rb', line 30

def respond_to?(method, include_private = false)
  super || object.respond_to?(method, include_private)
end