【发布时间】:2016-05-18 19:44:45
【问题描述】:
当通过alias_method创建的方法调用时,__callee__会忽略旧方法的名称(此处为xxx)并返回新方法的名称,如下所示:
class Foo
def xxx() __callee__ end
alias_method :foo, :xxx
end
Foo.new.foo # => :foo
即使xxx 是从超类继承的,这种行为仍然存在:
class Sup
def xxx() __callee__ end
end
class Bar < Sup
alias_method :bar, :xxx
end
Bar.new.bar # => :bar
鉴于上述两种情况,我希望通过模块包含 xxx 时会保持相同的行为。然而,事实并非如此:
module Mod
def xxx() __callee__ end
end
class Baz
include Mod
alias_method :baz, :xxx
end
Baz.new.baz # => :xxx
我希望返回值是:baz,而不是:xxx。
以上代码是使用 Ruby 2.3.1p112 执行的。这是__callee__ 实现中的错误吗?或者可能是alias_method?如果不是,谁能解释为什么模块包含的行为不同?
更新 1
我已经posted this to the Ruby bug tracker 试图激起答案。
更新 2
显然,我 not the only one 对这个问题感到惊讶。我想知道Revision 50728(这是为了解决Bug 11046: __callee__ returns incorrect method name in orphan proc)是否可能相关。
【问题讨论】:
-
非常有趣,肯定在 2.2 和 2.3 之间发生了变化。
__method__也一样。 -
@NilsLandt 你能举一个
__method__行为的例子吗?我用__method__替换了__callee__并为所有3 个案例返回了xxx。 Ruby 2.2 有什么不同吗?
标签: ruby inheritance metaprogramming alias-method