emery emery - 7 months ago 11
Ruby Question

Extending Modules from a gem instead of monkey patching

Assuming that "clean" Ruby monkey patching isn't an option, and all gem extension methods need to be completely contained within their own namespace, and given a structure like

module ARubyGem
class GemClassOne
def method1
# instance method to be available when calling extended module
end
def self.method2
# singleton method to also be available in extended module
end
end
end


Then which of these is the better way to extend a gem if the original gem code has some singleton methods that begin with "self"?

module ARubyGemExtension
class GemClassOneExtension < ARubyGem::GemClassOne
def method_to_override
# new code here
end
end
end


vs.

module ARubyGemExtension
include ARubyGem
class GemClassOneExtension
def method_to_override
# new code here
end
end
end

Answer

Seems like you would need to go with:

  module ARubyGemExtension
    class GemClassOneExtension < ARubyGem::GemClassOne
      def method_to_override
        # new code here
      end
    end
  end

(Remember to namespace GemClassOne.)

I don't know anything about the gem you're using, but unless it's specifically set up for providing methods through include, I think you may not get what you're after.