Is there a way to prevent a subclass from overriding a method that was
defined by an ancestor? Ideally, I would like to be able to prevent
changes at the granularity of a method rather than an entire class or
module. Thanks in advance,
In message “Prevent method override?” on 03/03/13, James Davis jd204c@nak.spak.nih.gov writes:
Is there a way to prevent a subclass from overriding a method that was
defined by an ancestor? Ideally, I would like to be able to prevent
changes at the granularity of a method rather than an entire class or
module. Thanks in advance,
def statement calls “method_added” after the method definition, so
you can prevent overriding by removing the method from the class and
then raising an error from the method_added class method.
Note that this scheme does not prevent removing and replacing in the
parent class.
On Thu, Mar 13, 2003 at 04:15:47AM +0900, James Davis wrote:
Is there a way to prevent a subclass from overriding a method that was
defined by an ancestor? Ideally, I would like to be able to prevent
changes at the granularity of a method rather than an entire class or
module. Thanks in advance,
Wednesday, March 12, 2003, 10:41:17 PM, you wrote:
def statement calls “method_added” after the method definition, so
you can prevent overriding by removing the method from the class and
then raising an error from the method_added class method.
Note that this scheme does not prevent removing and replacing in the
parent class.
this can be done by aliasing all existing methods and “restoring” them from aliases
Thanks so much. The latter problem is not an issue for me. Also, in
my app, overriding this base class is a protocol error, so I don’t
need to remove the method, just raise an error. This is what I came
up with in case anyone is interested:
Prevent a subclass from overriding a superclass’ method
class Base
def Base.meth0; puts ‘0’; end
private; def meth1; puts ‘A’; end
protected; def meth2; puts ‘B’; end
public; def meth3; puts ‘C’; end
def Base.prevent_override(id, methods, klass=‘’)
if methods.include?(id.id2name)
puts “Override of method #{klass}#{id.id2name} not allowed”
# raise error, remove method, whatever
end
end
def Base.method_added(id)
prevent_override(id, @@i_methods)
end
def Base.singleton_method_added(id)
if self == @@base_klass
prevent_override(id, @@s_methods, self.name+‘.’)
end
end
end
class Sub < Base
def Base.meth0; puts ‘ACK’; end #–> Error
def Sub.meth0; puts ‘NAK’; end #–> OK
def meth4; puts ‘D’; end #–> OK
def meth1; puts ‘B’; end #–> Error
end
Jim Davis -
···
On Thu, 13 Mar 2003 04:41:17 +0900, (Yukihiro Matsumoto) wrote:
def statement calls “method_added” after the method definition, so
you can prevent overriding by removing the method from the class and
then raising an error from the method_added class method.
Note that this scheme does not prevent removing and replacing in the
parent class.