Overriding a Module Method from a Gem in Rails

Overriding a module method from a gem in Rails

What you are doing will work, but your code needs to look like this:

module WillPaginate
module Finder
module ClassMethods
def paginate_by_sql(sql, options)
# your code here
end
end
end
end

In other words, go into finder.rb, delete everything except the module headers and the method you want to override, then save to a file in lib and include in environment.rb. Voila, instant monkey patch!

How to override a method of a ruby gem for certain conditions?

You can prepend the class being overriden and then use the conditional. This way your module will be the last in the ancestors chain and will be able to call super in order to use default behaviour

e.g.

module Override 
def to_s(*)
if self == 'a'
"===a==="
else
super
end
end
end
String.prepend(Override)

[9] pry(main)> String.new("a")
=> "a"
[10] pry(main)> String.new("a").to_s
=> "===a==="
[11] pry(main)> String.new("b").to_s
=> "b"

How can one override a class method inside a module inside a gem?

Try

OmniAuth::Configuration.class_eval do
def add_camelization(name, camelized)
...
end
end

Override initialize method of a gem?

Instead of overwriting the method, you can move your custom implementation into a separate module and prepend it to the Queue class:

# config/initializers/queue_extension.rb

module QueueExtension
def initialize(name, redis_or_options = {})
# Custom logic

super # <- as needed, invokes the original Redis::Unique::Queue#initialize
end
end

Redis::Unique::Queue.prepend(QueueExtension)

Using prepend puts the code "in front" of the existing code.

If Redis::Unique::Queue is not available at that point, you might have to require it.

Ruby on Rails: How can I override a method from a gem while calling the super method

Monkey patching it directly is hacky and overwrites the method altogether. You expected super to call the original implementation, but it is no longer there. Instead create a new module and include it there:

module CreateWithErrorLogging
def create(attributes = nil, &block)
begin
super
rescue Mongo::Error::OperationFailure => e
Rails.logger.error "failed to create notifications #{e.message}, #{e.backtrace}"
raise
end
end
end

Mongoid::Persistable::Creatable::ClassMethods.include CreateWithErrorLogging

How to override a method of a class from a gem in Rails?

Create a .rb file in config/initializers directory with the following code:

Youtube::Display.class_eval do
def find(id, options = {})
# Code here
end
end


Related Topics



Leave a reply



Submit