0

Let's say I have a hypothetical gem, my_gem, that defines the class AwesomeClass, and the gem includes a binary that will only work on AwesomeClass, but will load any code in my lib/ directory, say. I want to cleanly extend some of the class' methods, sometimes calling the equivalent of super.

Let's say it looks like this:

 class AwesomeClass def cool_method ... end end 

And over here, in my library code, I want to do something like:

 AwesomeClass.class_eval def cool_method (call the original method here) ... end end 

How would you do that? Is alias my only real option? Is there some nicer way I'm missing? Something other than class_eval?

0

1 Answer 1

1

Is alias my only real option?

Yes, if you want to open and directly modify a class. However, the better option is not opening 3rd party classes and monkey-patching them. You should either use inheritance, or composition: Build your own class which wraps an instance of AwesomeClass, provides its own cool_method that invokes the AwesomeClass method plus whatever additional functionality you need.

Sign up to request clarification or add additional context in comments.

3 Comments

How would you see that working if the gem only ever wants an AwesomeClass, and not my own?
@DanielBogan Then the Gem is built incorrectly, that isn't how Ruby's type system is meant to work. As long as your object supports the same method calls as an AwesomeClass, the gem shouldn't be able to reject it.
Yeah, that makes sense. Okay, rad, thank you!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.