Sha256: 79a2aca0b900eb162145baa91b0662ee11ed14b4fbd2d25ff8e70796566ac003

Contents?: true

Size: 1.18 KB

Versions: 27

Compression:

Stored size: 1.18 KB

Contents

# 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
class SmartDelegator
  attr_reader :object

  def initialize(object)
    @object = object
  end

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

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

  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
end

Version data entries

27 entries across 27 versions & 1 rubygems

Version Path
renalware-core-2.0.16 lib/smart_delegator.rb
renalware-core-2.0.15 lib/smart_delegator.rb
renalware-core-2.0.14 lib/smart_delegator.rb
renalware-core-2.0.13 lib/smart_delegator.rb
renalware-core-2.0.12 lib/smart_delegator.rb
renalware-core-2.0.11 lib/smart_delegator.rb
renalware-core-2.0.9 lib/smart_delegator.rb
renalware-core-2.0.8 lib/smart_delegator.rb
renalware-core-2.0.7 lib/smart_delegator.rb
renalware-core-2.0.5 lib/smart_delegator.rb
renalware-core-2.0.4 lib/smart_delegator.rb
renalware-core-2.0.3 lib/smart_delegator.rb
renalware-core-2.0.2 lib/smart_delegator.rb
renalware-core-2.0.1 lib/smart_delegator.rb
renalware-core-2.0.0 lib/smart_delegator.rb
renalware-core-2.0.0.pre.rc13 lib/smart_delegator.rb
renalware-core-2.0.0.pre.rc11 lib/smart_delegator.rb
renalware-core-2.0.0.pre.rc10 lib/smart_delegator.rb
renalware-core-2.0.0.pre.rc9 lib/smart_delegator.rb
renalware-core-2.0.0.pre.rc8 lib/smart_delegator.rb