Class: DumbDelegator

Inherits:
BasicObject
Defined in:
lib/dumb_delegator.rb,
lib/dumb_delegator/version.rb,
lib/dumb_delegator/triple_equal_ext.rb

Overview

class Coffee

def cost
  2
end

def origin
  "Colombia"
end

end

class Milk < DumbDelegator

def cost
  super + 0.4
end

end

class Sugar < DumbDelegator

def cost
  super + 0.2
end

end

coffee = Coffee.new Milk.new(coffee).origin #=> Colombia Sugar.new(Sugar.new(coffee)).cost #=> 2.4

cup_o_coffee = Sugar.new(Milk.new(coffee)) cup_o_coffee.cost #=> 2.6 cup_o_coffee.class #=> Coffee cup_o_coffee.is_a?(Coffee) #=> true cup_o_coffee.is_a?(Milk) #=> true cup_o_coffee.is_a?(Sugar) #=> true

Defined Under Namespace

Modules: TripleEqualExt

Constant Summary collapse

VERSION =
"1.0.0"

Instance Method Summary collapse

Constructor Details

#initialize(target) ⇒ DumbDelegator

Returns a new instance of DumbDelegator.


49
50
51
# File 'lib/dumb_delegator.rb', line 49

def initialize(target)
  __setobj__(target)
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

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


61
62
63
64
65
66
67
# File 'lib/dumb_delegator.rb', line 61

def method_missing(method, *args, &block)
  if @__dumb_target__.respond_to?(method)
    @__dumb_target__.__send__(method, *args, &block)
  else
    super
  end
end

Instance Method Details

#__getobj__Object

Returns The object calls are being delegated to.

Returns:

  • (Object)

    The object calls are being delegated to


74
75
76
# File 'lib/dumb_delegator.rb', line 74

def __getobj__
  @__dumb_target__
end

#__setobj__(obj) ⇒ Object

Parameters:

  • obj (Object)

    Change the object delegate to obj.

Raises:

  • (::ArgumentError)

79
80
81
82
# File 'lib/dumb_delegator.rb', line 79

def __setobj__(obj)
  raise ::ArgumentError, "Delegation to self is not allowed." if obj.__id__ == __id__
  @__dumb_target__ = obj
end

#inspectObject


53
54
55
# File 'lib/dumb_delegator.rb', line 53

def inspect
  "#<#{(class << self; self; end).superclass}:#{object_id} obj: #{__getobj__.inspect}>"
end

#marshal_dumpObject


84
85
86
87
88
89
# File 'lib/dumb_delegator.rb', line 84

def marshal_dump
  [
    :__v1__,
    __getobj__,
  ]
end

#marshal_load(data) ⇒ Object


91
92
93
94
95
96
97
# File 'lib/dumb_delegator.rb', line 91

def marshal_load(data)
  version, obj = data
  case version
  when :__v1__
    __setobj__(obj)
  end
end

#methods(all = true) ⇒ Object


57
58
59
# File 'lib/dumb_delegator.rb', line 57

def methods(all = true)
  __getobj__.methods(all) | super
end

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

Returns:

  • (Boolean)

69
70
71
# File 'lib/dumb_delegator.rb', line 69

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