我有一個大致具有以下結構的類:
class X
def initialize
@container = Container.new
....
end
def store
@container.get_store
end
def f
store.f
end
def g
store.g
end
def h
store.h
end
....
end
可以看出,我有幾個方法,它們只是“轉發”到store,只是那個store不是實體變數,而是無引數方法的結果。有沒有一種緊湊的方法來實作這種轉發?如果store總是回傳相同的物件,我可以這樣做:
class X
extend Forwardable
def initialize
container = Container.new
@store = container.the_store
end
def_delegator :@store, .f, :g, :h
end
但我不能依賴這個;@container.the_store可能會在實體的生命周期內發生變化。我考慮的一種選擇是
class X
[:f,:g,:h].each do |meth_sym|
define_method(meth_sym) do |*args|
store.public_send(meth_sym, *args)
end
end
def store
@container.get_store
end
end
但這看起來很笨拙。任何人都可以為我的問題提出不同的解決方案嗎?
uj5u.com熱心網友回復:
從檔案中Forwardable#def_instance_delegator:
accessor應該是方法名、實體變數名或常量名。
示例:(符號和字串都有效,.等效于::)
def_delegator :@store, :f # delegates f to instance variable @store
def_delegator :store, :f # delegates f to instance method store
def_delegator 'X.store', :f # delegates f to class method store
def_delegator 'X::Store', :f # delegates f to constant X::Store
既然你有一個實體方法,你想要:store(沒有@)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/464260.html
標籤:红宝石
