微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在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.jb51.cc/ruby/269230.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐