Skip to content

Ruby 方法分派:用 owner 与 super_method 定位覆盖 ​

给一个已有类加日志模块后,输出顺序发生了变化。只读类定义看不出原因,因为实际方法由接收者的查找链决定。先确定是哪一个对象在接收消息,再查当前方法由谁提供。

super 从哪里继续 ​

prepend 把模块放在类之前,include 把模块放在类之后,具体次序可从 ancestors 观察。同名方法里的 super 会从当前实现之后继续查找。有些方法直接返回而没有调用 super,这会在那一层结束调用,即使后面还有同名实现。Method#owner 给出当前绑定实现的所有者,super_method 可沿同一方法继续向下查。Ruby Module · Ruby Method

ruby
module Wrapped
  def label = "wrapped(#{super})"
end
module DefaultName
  def label = 'default'
end
class Record
  include DefaultName
  prepend Wrapped
  def label = "record(#{super})"
end

record = Record.new
call = record.method(:label)
owners = []
while call
  owners << call.owner.name
  call = call.super_method
end
p owners
puts record.label
def record.label = 'only this instance'
puts record.label
puts Record.new.label

得到 ["Wrapped", "Record", "DefaultName"],随后三行是 wrapped(record(default))、only this instance、wrapped(record(default))。后加的方法属于这个对象的单例类,所以另一个 Record 实例仍走原查找链。这里读取 owner.name 的过程在定义单例方法之前,避免把匿名单例类的名字误认为普通类名。

怎样排查一次意外覆盖 ​

如果只有某一对象出现异常,先对这个对象和新建的同类对象分别检查 method(:label).owner。两者一致时,再看该方法中的条件和实例状态。若加入模块后所有对象都改变,检查 ancestors 与 super_method 链,找到第一次与预期不一致的位置。练习时把 Wrapped 改为 include,预测哪些方法仍在查找链中、哪些会被调用,使用 owner 和真实返回值分别验证。方法链与枚举协议

继续阅读