我有一个简单的类用一个简单的方法定义有一个方法重新定义另一个类的方法
class Printer
def print
p '1'
end
end
现在我介绍一个单独的脚本,通过添加一些额外的东西打印重新定义了打印方法
class Printer
alias :old_print :print
def print
old_print
p '2'
end
end
我可以通过编程来实现吗?
module Test
def self.redefine_print(arg)
# redefine Printer's print method so that it will print all of the stuff it should
# print, followed by the arg I specified
end
end
因此,一个样品的相互作用可能看起来像
>>>a = Printer.new
>>>a.print
1
>>>Test.redefine_print("new stuff")
>>>a.print
1
new stuff
>>>Test.redefine_print("more")
>>>a.print
1
new stuff
more
如果现有实例是由变化的影响(因为打印机的任何实例将被创建,做它的打印,然后马上布置这是确定)
你有什么特别的理由要重新定义这个方法吗?为什么不在'Printer'上添加一个方法来添加更多要打印的内容? – 2013-02-18 19:51:54
你*正在以编程方式进行。没有理由不能在类定义之外做同样的事情。这就是说......目的是什么?如果你正在做的是添加在页眉/页脚/等。你不需要元编程。 – 2013-02-18 20:04:22
我使用的示例非常简化,纯粹是为了查看是否有可能或不可以(在另一个类中重新定义另一个方法)。我的解决方案可能会是@RenatoZannon提到的。 – MxyL 2013-02-18 22:34:44