Dorian Amouroux Dorian Amouroux - 4 months ago 7
Ruby Question

Override function within a third party module ruby

I'm trying to override a function that is inside two module from a third party library.

It looks like this :

module Omnigollum
module Helpers
def kick_back
redirect !request.referrer.nil? && request.referrer !~ /#{Regexp.escape(settings.send(:omnigollum)[:route_prefix])}\/.*/ ?
request.referrer:
'/'
halt
end
end
end


This function is used by other functions from this library, I need to completely override it.

I tried lot of solution given by other stackoverflow thread, but so far nothing works.

Here is what I have now :

module OmnigollumOverride
module Helpers
def kick_back
puts '=-=-=-=-=-=-=-=-=-==-=-'
puts '=-=-=-=-=-=-=-=-=-==-=-'
end
end
end

include Omnigollum
Omnigollum.module_eval { include OmnigollumOverride }


I just print some line to test if the function is correctly overridden.

Answer

Instead of:

include Omnigollum
Omnigollum.module_eval { include OmnigollumOverride }

call this once:

Omnigollum::Helpers.prepend OmnigollumOverride::Helpers

Prepending module places it on top of inheritance hierarchy. Whether you want to re-use the original behaviour, you might do:

def kick_back
  return super if SOME_CONDITION # call original method

  puts '=-=-=-=-=-=-=-=-=-==-=-'
  puts '=-=-=-=-=-=-=-=-=-==-=-'
end
Comments