在Ruby中覆盖方法调用?

前端之家收集整理的这篇文章主要介绍了在Ruby中覆盖方法调用?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试在调用特定类的任何方法时获得回调.
覆盖“发送”不起作用.似乎在普通的 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

我使用类<<重写了你的代码.自我语法打开元类,因为我不知道如何在类方法上使用alias_method.

原文链接:https://www.f2er.com/ruby/269230.html

猜你在找的Ruby相关文章