我想用一些方法編寫小類,這些方法屬於其他類,因此如何在其他類中定義方法,這些方法是現有的副本。我相信這是我不懂的metaprogramming magi。將方法從一個類複製到另一個類
class Foo
def initialize
# with blocks, I would just pass block, but this is methods
# so this won't work
Bar.class_eval(perform)
Bar.class_eval(process)
Bar.class_eval(save)
end
def perform
1+1
end
def process
# some code
end
def save
# some code
end
end
class Bar; end
foo = Foo.new
foo.perform
#=> 2
Bar.test
#=> 1
爲什麼我需要這個?我正在研究只需要三種方法就能上課的寶石。在初始化時(哪些病被隱藏在父類中)會將這些方法傳遞給不同的類。我可以用塊來做到這一點,但用方法來說,它更簡潔。
PS:這就像從一類到另一個
PSS複製方法:或者...怎麼方法轉換爲PROC,這樣我就可以把它傳遞給class_eval
也許你必須使用授權? http://khelll.com/blog/ruby/delegation-in-ruby/ – Fivell 2012-02-15 13:23:38
你不能只包含一個模塊嗎? – 2012-02-15 13:24:59
@Fivell,也許!我需要現在閱讀關於代表團 – fl00r 2012-02-15 13:26:06