Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
329 views
in Technique[技术] by (71.8m points)

ruby - Overriding a module method from a gem in Rails

The will_paginate gem is broken on my version of Oracle. The default paginate_by_sql method in the WillPaginate module is inserting an extra 'AS' into a query and causing it to fail.

The code itself is easily fixed, but I'm not sure of the best way to get Rails to pick up my change.

I don't want to change the code in the gem itself, as that will leave my code broken on other machines.

I tried creating an lib/test.rb file containing:

module WillPaginate
  def paginate_by_sql
    (my code goes here)
  end
end

and requiring it from environment.rb, but it's not picking up my changes. I also tried requiring it from controllers/application.rb, but again, not picking up my changes.

Temporarily, I got it to work by overriding the method within the specific model itself, but this is a bit of a hack, and means I can't use it on any of the other models in this project.

I'm sure there's an easy way to do this, but I'm not having any luck tracking it down using Google.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A more concise solution:

WillPaginate::Finder::ClassMethods.module_eval do
 def paginate_by_sql sql, options
   # Your code here
 end
end

Put the the code into an initializer file in config/initializers. This is the correct place to put code that needs to be run when the environment is loaded. It also better organises your code, making each file's intent clearer, thus bugs will be easier to track down. Do not clutter up environment.rb!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...