Delegator
言って:
このライブラリは、メソッド呼び出しをオブジェクトに委譲する 3 つの異なる方法を提供します。最も使いやすいのはSimpleDelegatorです。オブジェクトをコンストラクターに渡すと、オブジェクトがサポートするすべてのメソッドが委任されます。このオブジェクトは後で変更できます。
さて、シンボルの右側にある出力を見てください# =>
。
require 'delegate'
class Foo < SimpleDelegator
def meth
p 'new_meth'
end
end
class Bar
def meth
p 'old_meth'
end
def bar_meth
self.method(:meth)
end
end
bar = Bar.new # => #<Bar:0x8b31728>
foo = Foo.new(bar)
foo.__getobj__ # => #<Bar:0x8b31728>
foo.bar_meth # => #<Method: Bar#meth>
foo.method(:meth) # => #<Method: Foo#meth>
したがって、行を使用するfoo.method(:meth)
と、output( )は、#<Method: Foo#meth>
呼び出すたびに、クラスのメソッドが呼び出されることを確認します。foo.meth
meth
Foo
foo.bar_meth
#<Method: Bar#meth>
bar_meth
meth
Bar#meth
SimpleDelegator
それを言って:
Delegator の具体的な実装であるこのクラスは、サポートされているすべてのメソッド呼び出しをコンストラクターに渡されたオブジェクトに委譲する手段を提供し、委譲先のオブジェクトを後で # setobjで変更することさえできます。
はい、あなたの場合、を使用してオブジェクトがオブジェクトfoo
に設定されています。行の出力はそれを示しています。bar
#__setobj__
foo.__getobj__