我正在尝试在调用特定类的任何方法时获得回调.
覆盖“发送”不起作用.似乎在普通的 Ruby方法调用中不会调用send.以下面的例子为例.
覆盖“发送”不起作用.似乎在普通的 Ruby方法调用中不会调用send.以下面的例子为例.
class Test def self.items @items ||= [] end end
如果我们覆盖Test on Test,然后调用Test.items,则不会调用send.
我正在尝试做什么?
我宁愿不使用set_trace_func,因为它可能会大大减慢速度.
解决方法
使用别名或alias_method:
# the current implementation of Test,defined by someone else # and for that reason we might not be able to change it directly class Test def self.items @items ||= [] end end # we open the class again,probably in a completely different # file from the definition above class Test # open up the Metaclass,methods defined within this block become # class methods,just as if we had defined them with "def self.my_method" class << self # alias the old method as "old_items" alias_method :old_items,:items # redeclare the method -- this replaces the old items method,# but that's ok since it is still available under it's alias "old_items" def items # do whatever you want puts "items was called!" # then call the old implementation (make sure to call it last if you rely # on its return value) old_items end end end