Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a base class method non-overridable in ruby?

I have some base class A with a method that is not to be overridden.

class A
  def dont_override_me
    puts 'class A saying, "Thank you for not overriding me!"'
  end
end

And another class B that extends A and tries to override the dont_override_me method.

class B < A
  def dont_override_me
    puts 'class B saying, "This is my implementation!"'        
  end
end

If I instantiate B and call dont_override_me, class B's instance method will be called.

b = B.new
b.dont_override_me # => class B saying, "This is my implementation!"

This is because of ruby's properties. Understandable.

However, how do I force the base class method dont_override_me to be non-overridable by it's derived classes? I could not find a keyword like final in java for ruby. In C++, the base class methods can be made non-virtual so that they become non-overridable by the derived classes. How do I achieve this in ruby?

like image 727
Chirantan Avatar asked Dec 23 '22 12:12

Chirantan


2 Answers

You can do it, by hooking the change event and changing it back, but it seems a bit smelly to me:

http://scie.nti.st/2008/9/17/making-methods-immutable-in-ruby

It's one of those things that sort of defines Ruby, so fighting against it seems a little pointless imo. If someone redefines something so it breaks horribly.. that's their problem ;-)

like image 161
Steven Robbins Avatar answered Jan 07 '23 11:01

Steven Robbins


Here's a way to do it: http://www.thesorensens.org/2006/10/06/final-methods-in-ruby-prevent-method-override/

This has also been packaged into a gem called "finalizer" (gem install finalizer)

This makes use of the method_added callback and compares the new method name with a list of methods that you wish to make final.

like image 38
Gdeglin Avatar answered Jan 07 '23 13:01

Gdeglin