加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

在Ruby中覆盖方法调用?

发布时间:2020-12-17 04:31:26 所属栏目:百科 来源:网络整理
导读:我正在尝试在调用特定类的任何方法时获得回调. 覆盖“发送”不起作用.似乎在普通的 Ruby方法调用中不会调用send.以下面的例子为例. class Test def self.items @items ||= [] endend 如果我们覆盖Test on Test,然后调用Test.items,则不会调用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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读