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?

waferbaby
  • 21
  • 1
  • 5

1 Answers1

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.

user229044
  • 232,980
  • 40
  • 330
  • 338
  • How would you see that working if the gem only ever wants an `AwesomeClass`, and not my own? – waferbaby Feb 15 '17 at 12:21
  • 1
    @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. – user229044 Feb 15 '17 at 12:22
  • Yeah, that makes sense. Okay, rad, thank you! – waferbaby Feb 15 '17 at 12:23