【发布时间】:2012-03-06 20:14:13
【问题描述】:
我想用一些方法编写小类,这些方法实际上属于其他类,那么如何在其他类中定义现有方法的副本。我相信这是我不懂的元编程魔术师。
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
为什么我需要这个?我正在研究仅用三种方法上课的 gem。在初始化(将隐藏在父类中)时,它将将此方法传递给不同的类。我可以用积木来做这个,但是用方法就更干净了。
PS:这就像将方法从一个类复制到另一个类
PSS:或者......如何将方法转换为proc,所以我可以将它传递给class_eval
【问题讨论】:
-
也许你必须使用委托? khelll.com/blog/ruby/delegation-in-ruby
-
你不能只包含一个模块吗?
-
@Fivell,也许吧!我现在需要阅读有关委托的内容
-
添加了示例链接
-
@Sergio Tulentsev 在这种情况下 - 否
标签: ruby metaprogramming proc