Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby reopening classes -- can overridden methods be accessed?

I know if I subclass the String class and override its capitalize method, I can call the String class' version of capitalize with super. What if instead I reopened the String class and rewrote the capitalize method? Is there a way I can call the previous version of that method?

like image 517
Kvass Avatar asked Jun 08 '11 19:06

Kvass


People also ask

What are open classes in Ruby?

This is possible because Ruby supports a concept known as “Open classes”, which lets you do exactly this, i.e. extend an existing class, without altering the original class-block. “Monkey Patching” is something that's made possible thanks to the concept of open classes.

How do you override a class in Ruby?

Override means two methods having same name but doing different tasks. It means that one of the methods overrides another method. If there is any method in the superclass and a method with the same name in its subclass, then by executing these methods, method of the corresponding class will be executed.

How to override inheritance?

To override an inherited method, the method in the child class must have the same name, parameter list, and return type (or a subclass of the return type) as the parent method. Any method that is called must be defined within its own class or its superclass. You may see the @Override annotation above a method.

Does Ruby have class methods?

There are two standard approaches for defining class method in Ruby. The first one is the “def self. method” (let's call it Style #1), and the second one is the “class << self” (let's call it Style #2).


1 Answers

Not out of the box. A common approach is to rename the existing method to a new name. Then, in your rewritten version, call the old method by the new name.

def String
    alias to_i old_to_i
    def to_i
       #add your own functionality here
       old_to_i
    end
end

You might also want to look at alias_method_chain, which does some of this for you.

like image 173
Jacob Mattison Avatar answered Sep 19 '22 19:09

Jacob Mattison