[英]Ruby Class Inheritance: How to preven a public method from beeing overwritten in the child classes
Is it possible to prevent a public method from being overwritten in the child classes? 是否可以防止公共方法被子类覆盖?
class Parent
def some_method
#important stuff that should never be overwritten
end
end
class Child < Parent
def some_method
#should not be possible to overwrite (raise an error if a child class tries to do it)
end
end
Thanks! 谢谢!
You can use 'method_added' and 'inherited' hook for this purpose: 您可以使用'method_added'和'inherited'钩子来实现此目的:
class Foo
def self.inherited(sub)
sub.class_eval do
def self.method_added(name)
if name == :some_method
remove_method name
raise Exception, "Can't override #{name} method"
end
end
end
end
end
class Bar < Foo
end
class Bar
def some_method
end
end
# => Exception: Can't override some_method method
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.