Class: SmartDelegator
- Inherits:
-
Object
- Object
- SmartDelegator
- 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
-
#object ⇒ Object
readonly
Returns the value of attribute object.
Instance Method Summary collapse
-
#initialize(object) ⇒ SmartDelegator
constructor
A new instance of SmartDelegator.
- #inspect ⇒ Object
- #method_missing(method, *args, &block) ⇒ Object
- #respond_to?(method, include_private = false) ⇒ Boolean
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
#object ⇒ Object (readonly)
Returns the value of attribute object.
24 25 26 |
# File 'lib/smart_delegator.rb', line 24 def object @object end |
Instance Method Details
#inspect ⇒ Object
34 35 36 |
# File 'lib/smart_delegator.rb', line 34 def inspect "SmartDelegator(#{object.inspect})" end |
#respond_to?(method, include_private = false) ⇒ 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 |