如何查看 Ruby 中类层次结构中方法的定义和重写位置?
有没有办法以编程方式知道某个方法是否已被子类覆盖?像这样工作的东西:
class BaseModel
def create
puts "superclass"
end
end
class SomeModel < BaseModel
def create
puts "subclass"
end
end
puts SomeModel.overridden_instance_methods #=> [:create]
有什么想法吗?
Is there a way to know whether or not a method has been overridden by a subclass programmatically? Something that works like this:
class BaseModel
def create
puts "superclass"
end
end
class SomeModel < BaseModel
def create
puts "subclass"
end
end
puts SomeModel.overridden_instance_methods #=> [:create]
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
false
使instance_methods
不包含继承的方法。然后,我们使用集合交集来查找先前在 BaseModel(或 Object)上定义的 SomeModel 上定义的所有方法。The
false
makesinstance_methods
not include inherited methods. We then use set intersection to find all the methods that were defined on SomeModel which have previously been defined on BaseModel (or Object).