Class: DumbDelegator

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

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.1.0"

Instance Method Summary collapse

Constructor Details

#initialize(target) ⇒ DumbDelegator

Returns a new instance of DumbDelegator.

[View source]

51
52
53
# File 'lib/dumb_delegator.rb', line 51

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

[View source]

63
64
65
66
67
68
69
# File 'lib/dumb_delegator.rb', line 63

def method_missing(method, *args, &block)
  if __getobj__.respond_to?(method)
    __getobj__.__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

[View source]

76
77
78
# File 'lib/dumb_delegator.rb', line 76

def __getobj__
  @__dumb_target__
end

#__setobj__(obj) ⇒ Object

Parameters:

  • obj (Object)

    Change the object delegate to obj.

Raises:

  • (::ArgumentError)
[View source]

81
82
83
84
# File 'lib/dumb_delegator.rb', line 81

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

#inspectObject

[View source]

55
56
57
# File 'lib/dumb_delegator.rb', line 55

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

#marshal_dumpObject

[View source]

86
87
88
89
90
91
# File 'lib/dumb_delegator.rb', line 86

def marshal_dump
  [
    :__v1__,
    __getobj__
  ]
end

#marshal_load(data) ⇒ Object

[View source]

93
94
95
96
97
98
99
# File 'lib/dumb_delegator.rb', line 93

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

#methods(all = true) ⇒ Object

[View source]

59
60
61
# File 'lib/dumb_delegator.rb', line 59

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

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

Returns:

  • (Boolean)
[View source]

71
72
73
# File 'lib/dumb_delegator.rb', line 71

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