我想用一些方法编写小类,这些方法属于其他类,因此如何在其他类中定义方法,这些方法是现有的副本。我相信这是我不懂的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