ruby-覆盖方法,然后还原 [英] ruby - override method and then revert

查看:107
本文介绍了ruby-覆盖方法,然后还原的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找到一种方法,可以覆盖方法,执行某些操作,然后进行还原,而不会留下任何假象.

I am trying to find a way that I can override a method, do something, and then revert without leaving any artifacts around.

我已经使用Mocha实现了这一点,但是显然这不会在生产应用程序中实现.请注意,新方法具有参数,而旧方法则没有.

I have implemented this using mocha but obviously this is not going to fly in a production app. Notice the new method has parameters and the old one does not.

示例如下

require 'rubygems'
require 'mocha'

class Example

  def to_something
    self.stubs(:attribs => other(1))
    r = attribs_caller
    self.unstub(:attribs)
    r
  end

  def other(int)
    {"other" => int }
  end

  def attribs_caller
    attribs
  end

  def attribs
    {"this" => 1 }
  end

end

a1 = Example.new

puts a1.attribs_caller  #=> this1
puts a1.to_something    #=> other1
puts a1.attribs_caller  #=> this1

推荐答案

另一种无需创建额外方法的方法是:

Another way to do that, without creating an extra method, is this:

class Foo
  def bar
    :old_method
  end
end

Foo.new.foo # => :old_method

$old_method = Foo.new.method(:bar)

class Foo
  def bar
    :new_method
  end
end

Foo.new.foo # => :new_method

class Foo
  define_method($old_method.name, &$old_method)
end

Foo.new.foo # => :old_method

我认为这比使用别名方法更好.在Ruby中,方法也是对象.在破坏对象(方法)与类的关联之前,我只是引用对象.之后,我添加相同的方法.如果您使用undef关键字从类中删除该方法,它也将起作用.糟糕的是,您必须具有该类的对象才能引用该方法.

I think that this is better than using an alias method. In Ruby methods are, also, objects. I just take the reference of the object before destructing the association of the object (the method) with the class. After I add the same method. It also works if you use the undef keyword to remove the method from the class. The bad point is that you have to have an object of the class to take the reference of the method.

这篇关于ruby-覆盖方法,然后还原的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆