Overwriting a dependency gem class which inherits from a parent class
If I am using blah
gem, and this gem has a class called foo
which inherits from bar
. But I want to change this class on this gem. Is there a way I can do that, I have seen ways to overwrite methods on classes from gems but not to overwrite the actual classes.
eg.
The class I want to overwrite is as follows:
class foo < bar
def some_method
end
def another_method
end
end
How I want to overwrite this class:
class foo < not_bar
def a_different_some_method
end
def a_different_another_method
end
end
CodePudding user response:
No, you can't actually change the parent class without basically rewriting the subclass. If you only have two methods in each class that's probably fine, but Ruby classes use single-inheritance, so you can't re-assign a subclass to a different superclass without redefining it. You can, however, do any of the following:
- Re-open the class and redefine its methods.
- Prepend a module to redefine the behavior of existing methods.
- Add or modify methods for the singleton class, or on a singleton instance of that class.
- If your class is inheriting from Delegator, you can change the delegate class with #__setobj__.
Since you haven't really defined a use case, it's hard to tell which method would be best for you. Once the parent class is defined, though, it stays defined, so you'll have to do whatever you're trying to do another way.