当猴子修补实例方法时,您可以从新实现中调用重写的方法吗?

发布于 2024-10-08 06:16:37 字数 236 浏览 6 评论 0原文

假设我正在修补类中的方法,我如何从重写方法中调用重写方法?即有点像 super

例如

class Foo
  def bar()
    "Hello"
  end
end 

class Foo
  def bar()
    super() + " World"
  end
end

>> Foo.new.bar == "Hello World"

Say I am monkey patching a method in a class, how could I call the overridden method from the overriding method? I.e. Something a bit like super

E.g.

class Foo
  def bar()
    "Hello"
  end
end 

class Foo
  def bar()
    super() + " World"
  end
end

>> Foo.new.bar == "Hello World"

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

傾城如夢未必闌珊 2024-10-15 06:16:37

编辑:自从我最初写这个答案以来已经过去了 9 年,它值得进行一些整容手术以使其保持最新状态。

您可以在此处查看编辑前的最新版本。


您不能通过名称或关键字覆盖方法来调用。这是应避免猴子修补并首选继承的众多原因之一,因为显然您可以调用重写方法。

避免 Monkey 修补

继承

因此,如果可能的话,您应该更喜欢这样的东西:

class Foo
  def bar
    'Hello'
  end
end 

class ExtendedFoo < Foo
  def bar
    super + ' World'
  end
end

ExtendedFoo.new.bar # => 'Hello World'

如果您控制 Foo 对象的创建,那么这种方法就有效。只需更改创建 Foo 的每个位置即可创建 ExtendedFoo。如果您使用依赖注入设计模式,即工厂方法设计模式 抽象工厂设计模式 或类似的东西,因为在这种情况下,只有一个地方需要更改。

委托

如果您控制Foo对象的创建,例如因为它们是由您无法控制的框架创建的(例如 例如),然后您可以使用包装设计模式

require 'delegate'

class Foo
  def bar
    'Hello'
  end
end 

class WrappedFoo < DelegateClass(Foo)
  def initialize(wrapped_foo)
    super
  end

  def bar
    super + ' World'
  end
end

foo = Foo.new # this is not actually in your code, it comes from somewhere else

wrapped_foo = WrappedFoo.new(foo) # this is under your control

wrapped_foo.bar # => 'Hello World'

基本上,在系统的边界,Foo 对象进入您的代码,您将其包装到另一个对象中,然后在代码中的其他地方使用该对象而不是原始对象。

这使用 Object#DelegateClass来自 delegate stdlib 中的库。

“干净”的猴子补丁

Module#prepend: Mixin Prepending

上述两种方法都需要更改系统以避免猴子修补。本节展示了猴子修补的首选且侵入性最小的方法,如果无法更改系统的话。

Module#prepend 已添加到或多或少地支持这个用例。 Module#prependModule#include 做同样的事情,除了它直接在类下面的 mixin 中混合:

class Foo
  def bar
    'Hello'
  end
end 

module FooExtensions
  def bar
    super + ' World'
  end
end

class Foo
  prepend FooExtensions
end

Foo.new.bar # => 'Hello World'

注意:我还写了一个关于此问题中的 Module#prepend 的一些信息:Ruby 模块前置与派生

Mixin 继承(破碎)

我看到有些人尝试(并询问为什么它在 StackOverflow 上不起作用)这样的事情,即 include 混合而不是 prepend ing it:

class Foo
  def bar
    'Hello'
  end
end 

module FooExtensions
  def bar
    super + ' World'
  end
end

class Foo
  include FooExtensions
end

不幸的是,这行不通。这是一个好主意,因为它使用继承,这意味着您可以使用 super。但是, Module#include 插入继承层次结构中类之上的 mixin,这意味着 FooExtensions#bar 永远不会被调用(如果被调用,< code>super 实际上不会引用 Foo#bar,而是引用不存在的 Object#bar),因为 Foo#bar< /code> 总是会首先被找到。

方法包装

最大的问题是:我们如何才能保留 bar 方法,而不实际保留实际方法?正如经常出现的那样,答案就在于函数式编程。我们将该方法作为实际的对象进行保存,并使用闭包(即块)来确保我们并且只有我们保存该对象:

class Foo
  def bar
    'Hello'
  end
end 

class Foo
  old_bar = instance_method(:bar)

  define_method(:bar) do
    old_bar.bind(self).() + ' World'
  end
end

Foo.new.bar # => 'Hello World'

这非常干净:由于 old_bar 只是一个局部变量,它会在类主体末尾超出范围,并且不可能从任何地方访问它,甚至 使用反射!由于 Module#define_method 需要一个块,并且块靠近其周围的词法环境(这就是为什么我们在这里使用 define_method 而不是 def),it (并且它)仍然可以访问old_bar,即使它超出了范围。

简短说明:

old_bar = instance_method(:bar)

这里我们将 bar 方法包装到 UnboundMethod 中 方法对象并将其分配给局部变量old_bar。这意味着,即使在 bar 被覆盖之后,我们现在也有办法保留它。

old_bar.bind(self)

这有点棘手。基本上,在 Ruby(以及几乎所有基于单分派的 OO 语言)中,方法绑定到特定的接收者对象,在 Ruby 中称为 self。换句话说:方法总是知道它被调用的对象是什么,它知道它的 self 是什么。但是,我们直接从类中获取方法,它如何知道它的 self 是什么?

嗯,事实并非如此,这就是为什么我们需要 bind 我们的 UnboundMethod 首先到一个对象,它将返回一个 Method 我们可以调用的对象。 (UnboundMethod 无法被调用,因为它们在不知道自己的自身的情况下不知道要做什么。)

我们将它绑定到什么地方?我们只需将它绑定到我们自己,这样它的行为就会完全像原来的bar一样!

最后,我们需要调用从 bind 返回的 Method。在 Ruby 1.9 中,有一些漂亮的新语法 (.()),但如果您使用的是 1.8,则可以简单地使用 调用方法;无论如何,这就是 .() 被翻译成的内容。

以下是其他几个问题,其中解释了其中一些概念:

“肮脏的”猴子修补

alias_method

我们在猴子修补中遇到的问题就是当我们覆盖方法的时候,方法就没有了,所以我们就不能再调用它了。所以,让我们制作一个备份副本!

class Foo
  def bar
    'Hello'
  end
end 

class Foo
  alias_method :old_bar, :bar

  def bar
    old_bar + ' World'
  end
end

Foo.new.bar # => 'Hello World'
Foo.new.old_bar # => 'Hello'

问题是我们现在用多余的 old_bar 方法污染了命名空间。此方法将显示在我们的文档中,它将显示在我们的 IDE 中的代码完成中,它将显示在反射期间。另外,它仍然可以被调用,但想必我们猴子修补了它,因为我们一开始就不喜欢它的行为,所以我们可能不希望其他人调用它。

尽管事实上它有一些不良特性,但不幸的是它已经通过 AciveSupport 的 变得流行起来Module#alias_method_chain

旁白:细化

如果您只需要少数情况下的不同行为特定的地方而不是遍及整个系统,您可以使用Refinements将猴子补丁限制在特定的范围内。我将在这里使用上面的 Module#prepend 示例进行演示:

class Foo
  def bar
    'Hello'
  end
end 

module ExtendedFoo
  module FooExtensions
    def bar
      super + ' World'
    end
  end

  refine Foo do
    prepend FooExtensions
  end
end

Foo.new.bar # => 'Hello'
# We haven’t activated our Refinement yet!

using ExtendedFoo
# Activate our Refinement

Foo.new.bar # => 'Hello World'
# There it is!

您可以在这个问题中看到使用 Refinements 的更复杂的示例:如何为特定方法启用猴子补丁?


废弃的想法

在 Ruby 社区确定 Module#prepend 之前,有多种不同的想法可供您选择有时可能会在较早的讨论中看到引用。所有这些都包含在 Module#prepend 中。

方法组合器

一种想法是来自 CLOS 的方法组合器的想法。这基本上是面向方面编程子集的一个非常轻量级的版本。

使用像您这样的语法

class Foo
  def bar:before
    # will always run before bar, when bar is called
  end

  def bar:after
    # will always run after bar, when bar is called
    # may or may not be able to access and/or change bar’s return value
  end
end

就可以“挂钩” bar 方法的执行。

然而,尚不清楚是否以及如何在 bar:after 中访问 bar 的返回值。也许我们可以(ab)使用 super 关键字?

class Foo
  def bar
    'Hello'
  end
end 

class Foo
  def bar:after
    super + ' World'
  end
end

替换

before 组合器相当于在 mixin 前面添加一个重写方法,该方法在方法的最末尾调用 super。同样,后组合器相当于在 mixin 前面添加一个重写方法,该方法在方法的最开始处调用 super。

您还可以在调用 super 之前执行一些操作,您可以多次调用 super,并且检索和操作 super code> 的返回值,使得 prepend 比方法组合器更强大。

class Foo
  def bar:before
    # will always run before bar, when bar is called
  end
end

# is the same as

module BarBefore
  def bar
    # will always run before bar, when bar is called
    super
  end
end

class Foo
  prepend BarBefore
end

class Foo
  def bar:after
    # will always run after bar, when bar is called
    # may or may not be able to access and/or change bar’s return value
  end
end

# is the same as

class BarAfter
  def bar
    original_return_value = super
    # will always run after bar, when bar is called
    # has access to and can change bar’s return value
  end
end

class Foo
  prepend BarAfter
end

old 关键字

这个想法添加了一个类似于 super 的新关键字,它允许您以 super<相同的方式调用覆盖方法/code> 允许您调用重写方法:

class Foo
  def bar
    'Hello'
  end
end 

class Foo
  def bar
    old + ' World'
  end
end

Foo.new.bar # => 'Hello World'

主要问题是它向后不兼容:如果您有名为old的方法,您将无法再呼唤它!

prepended mixin 中的重写方法中替换

super 本质上与本提案中的old 相同。

redef 关键字

与上面类似,但我们没有为调用覆盖的方法添加新关键字并单独保留def,而是为重新定义方法。这是向后兼容的,因为无论如何目前的语法都是非法的:

class Foo
  def bar
    'Hello'
  end
end 

class Foo
  redef bar
    old + ' World'
  end
end

Foo.new.bar # => 'Hello World'

我们也可以在 redefsuper 的含义,而不是添加两个新关键字>:

class Foo
  def bar
    'Hello'
  end
end 

class Foo
  redef bar
    super + ' World'
  end
end

Foo.new.bar # => 'Hello World'

替换

redef方法相当于覆盖前置混合中的方法。重写方法中的 super 的行为类似于本提案中的 superold

EDIT: It has been 9 years since I originally wrote this answer, and it deserves some cosmetic surgery to keep it current.

You can see the last version before the edit here.


You can’t call the overwritten method by name or keyword. That’s one of the many reasons why monkey patching should be avoided and inheritance be preferred instead, since obviously you can call the overridden method.

Avoiding Monkey Patching

Inheritance

So, if at all possible, you should prefer something like this:

class Foo
  def bar
    'Hello'
  end
end 

class ExtendedFoo < Foo
  def bar
    super + ' World'
  end
end

ExtendedFoo.new.bar # => 'Hello World'

This works, if you control creation of the Foo objects. Just change every place which creates a Foo to instead create an ExtendedFoo. This works even better if you use the Dependency Injection Design Pattern, the Factory Method Design Pattern, the Abstract Factory Design Pattern or something along those lines, because in that case, there is only place you need to change.

Delegation

If you do not control creation of the Foo objects, for example because they are created by a framework that is outside of your control (like for example), then you could use the Wrapper Design Pattern:

require 'delegate'

class Foo
  def bar
    'Hello'
  end
end 

class WrappedFoo < DelegateClass(Foo)
  def initialize(wrapped_foo)
    super
  end

  def bar
    super + ' World'
  end
end

foo = Foo.new # this is not actually in your code, it comes from somewhere else

wrapped_foo = WrappedFoo.new(foo) # this is under your control

wrapped_foo.bar # => 'Hello World'

Basically, at the boundary of the system, where the Foo object comes into your code, you wrap it into another object, and then use that object instead of the original one everywhere else in your code.

This uses the Object#DelegateClass helper method from the delegate library in the stdlib.

“Clean” Monkey Patching

Module#prepend: Mixin Prepending

The two methods above require changing the system to avoid monkey patching. This section shows the preferred and least invasive method of monkey patching, should changing the system not be an option.

Module#prepend was added to support more or less exactly this use case. Module#prepend does the same thing as Module#include, except it mixes in the mixin directly below the class:

class Foo
  def bar
    'Hello'
  end
end 

module FooExtensions
  def bar
    super + ' World'
  end
end

class Foo
  prepend FooExtensions
end

Foo.new.bar # => 'Hello World'

Note: I also wrote a little bit about Module#prepend in this question: Ruby module prepend vs derivation

Mixin Inheritance (broken)

I have seen some people try (and ask about why it doesn’t work here on StackOverflow) something like this, i.e. includeing a mixin instead of prepending it:

class Foo
  def bar
    'Hello'
  end
end 

module FooExtensions
  def bar
    super + ' World'
  end
end

class Foo
  include FooExtensions
end

Unfortunately, that won’t work. It’s a good idea, because it uses inheritance, which means that you can use super. However, Module#include inserts the mixin above the class in the inheritance hierarchy, which means that FooExtensions#bar will never be called (and if it were called, the super would not actually refer to Foo#bar but rather to Object#bar which doesn’t exist), since Foo#bar will always be found first.

Method Wrapping

The big question is: how can we hold on to the bar method, without actually keeping around an actual method? The answer lies, as it does so often, in functional programming. We get a hold of the method as an actual object, and we use a closure (i.e. a block) to make sure that we and only we hold on to that object:

class Foo
  def bar
    'Hello'
  end
end 

class Foo
  old_bar = instance_method(:bar)

  define_method(:bar) do
    old_bar.bind(self).() + ' World'
  end
end

Foo.new.bar # => 'Hello World'

This is very clean: since old_bar is just a local variable, it will go out of scope at the end of the class body, and it is impossible to access it from anywhere, even using reflection! And since Module#define_method takes a block, and blocks close over their surrounding lexical environment (which is why we are using define_method instead of def here), it (and only it) will still have access to old_bar, even after it has gone out of scope.

Short explanation:

old_bar = instance_method(:bar)

Here we are wrapping the bar method into an UnboundMethod method object and assigning it to the local variable old_bar. This means, we now have a way to hold on to bar even after it has been overwritten.

old_bar.bind(self)

This is a bit tricky. Basically, in Ruby (and in pretty much all single-dispatch based OO languages), a method is bound to a specific receiver object, called self in Ruby. In other words: a method always knows what object it was called on, it knows what its self is. But, we grabbed the method directly from a class, how does it know what its self is?

Well, it doesn’t, which is why we need to bind our UnboundMethod to an object first, which will return a Method object that we can then call. (UnboundMethods cannot be called, because they don’t know what to do without knowing their self.)

And what do we bind it to? We simply bind it to ourselves, that way it will behave exactly like the original bar would have!

Lastly, we need to call the Method that is returned from bind. In Ruby 1.9, there is some nifty new syntax for that (.()), but if you are on 1.8, you can simply use the call method; that’s what .() gets translated to anyway.

Here are a couple of other questions, where some of those concepts are explained:

“Dirty” Monkey Patching

alias_method chain

The problem we are having with our monkey patching is that when we overwrite the method, the method is gone, so we cannot call it anymore. So, let’s just make a backup copy!

class Foo
  def bar
    'Hello'
  end
end 

class Foo
  alias_method :old_bar, :bar

  def bar
    old_bar + ' World'
  end
end

Foo.new.bar # => 'Hello World'
Foo.new.old_bar # => 'Hello'

The problem with this is that we have now polluted the namespace with a superfluous old_bar method. This method will show up in our documentation, it will show up in code completion in our IDEs, it will show up during reflection. Also, it still can be called, but presumably we monkey patched it, because we didn’t like its behavior in the first place, so we might not want other people to call it.

Despite the fact that this has some undesirable properties, it has unfortunately become popularized through AciveSupport’s Module#alias_method_chain.

An aside: Refinements

In case you only need the different behavior in a few specific places and not throughout the whole system, you can use Refinements to restrict the monkey patch to a specific scope. I am going to demonstrate it here using the Module#prepend example from above:

class Foo
  def bar
    'Hello'
  end
end 

module ExtendedFoo
  module FooExtensions
    def bar
      super + ' World'
    end
  end

  refine Foo do
    prepend FooExtensions
  end
end

Foo.new.bar # => 'Hello'
# We haven’t activated our Refinement yet!

using ExtendedFoo
# Activate our Refinement

Foo.new.bar # => 'Hello World'
# There it is!

You can see a more sophisticated example of using Refinements in this question: How to enable monkey patch for specific method?


Abandoned ideas

Before the Ruby community settled on Module#prepend, there were multiple different ideas floating around that you may occasionally see referenced in older discussions. All of these are subsumed by Module#prepend.

Method Combinators

One idea was the idea of method combinators from CLOS. This is basically a very lightweight version of a subset of Aspect-Oriented Programming.

Using syntax like

class Foo
  def bar:before
    # will always run before bar, when bar is called
  end

  def bar:after
    # will always run after bar, when bar is called
    # may or may not be able to access and/or change bar’s return value
  end
end

you would be able to “hook into” the execution of the bar method.

It is however not quite clear if and how you get access to bar’s return value within bar:after. Maybe we could (ab)use the super keyword?

class Foo
  def bar
    'Hello'
  end
end 

class Foo
  def bar:after
    super + ' World'
  end
end

Replacement

The before combinator is equivalent to prepending a mixin with an overriding method that calls super at the very end of the method. Likewise, the after combinator is equivalent to prepending a mixin with an overriding method that calls super at the very beginning of the method.

You can also do stuff before and after calling super, you can call super multiple times, and both retrieve and manipulate super’s return value, making prepend more powerful than method combinators.

class Foo
  def bar:before
    # will always run before bar, when bar is called
  end
end

# is the same as

module BarBefore
  def bar
    # will always run before bar, when bar is called
    super
  end
end

class Foo
  prepend BarBefore
end

and

class Foo
  def bar:after
    # will always run after bar, when bar is called
    # may or may not be able to access and/or change bar’s return value
  end
end

# is the same as

class BarAfter
  def bar
    original_return_value = super
    # will always run after bar, when bar is called
    # has access to and can change bar’s return value
  end
end

class Foo
  prepend BarAfter
end

old keyword

This idea adds a new keyword similar to super, which allows you to call the overwritten method the same way super lets you call the overridden method:

class Foo
  def bar
    'Hello'
  end
end 

class Foo
  def bar
    old + ' World'
  end
end

Foo.new.bar # => 'Hello World'

The main problem with this is that it is backwards incompatible: if you have method called old, you will no longer be able to call it!

Replacement

super in an overriding method in a prepended mixin is essentially the same as old in this proposal.

redef keyword

Similar to above, but instead of adding a new keyword for calling the overwritten method and leaving def alone, we add a new keyword for redefining methods. This is backwards compatible, since the syntax currently is illegal anyway:

class Foo
  def bar
    'Hello'
  end
end 

class Foo
  redef bar
    old + ' World'
  end
end

Foo.new.bar # => 'Hello World'

Instead of adding two new keywords, we could also redefine the meaning of super inside redef:

class Foo
  def bar
    'Hello'
  end
end 

class Foo
  redef bar
    super + ' World'
  end
end

Foo.new.bar # => 'Hello World'

Replacement

redefining a method is equivalent to overriding the method in a prepended mixin. super in the overriding method behaves like super or old in this proposal.

热风软妹 2024-10-15 06:16:37

看一下别名方法,这是一种将方法重命名为新名称的方法。

有关更多信息和起点,请查看这篇替换方法文章(尤其是第一部分)。
Ruby API 文档 还提供了(不太详细的)示例。

Take a look at aliasing methods, this is kind of renaming the method to a new name.

For more information and a starting point take a look at this replacing methods article (especially the first part).
The Ruby API docs, also provides (a less elaborate) example.

挽梦忆笙歌 2024-10-15 06:16:37

将进行覆盖的类必须在包含原始方法的类之后重新加载,因此在将进行覆盖的文件中require它。

The class that will make override must to be reloaded after class that contains the original method, so require it in the file that will make overrride.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文