从 Rails 中的 gem 覆盖模块方法 [英] Overriding a module method from a gem in Rails

查看:11
本文介绍了从 Rails 中的 gem 覆盖模块方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

will_paginate gem 在我的 Oracle 版本上已损坏.WillPaginate 模块中的默认 paginate_by_sql 方法会在查询中插入额外的AS"并导致查询失败.

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.

代码本身很容易修复,但我不确定让 Rails 接受我的更改的最佳方法.

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

我不想更改 gem 本身的代码,因为这会使我的代码在其他机器上损坏.

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

我尝试创建一个 lib/test.rb 文件,其中包含:

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

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

并从 environment.rb 中要求它,但它没有接受我的更改.我也尝试从 controllers/application.rb 中要求它,但同样,没有接受我的更改.

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.

我确信有一种简单的方法可以做到这一点,但我没有任何运气使用 Google 跟踪它.

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

推荐答案

你正在做的将工作,但你的代码需要看起来像这样:

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

换句话说,进入 finder.rb,删除除模块头和要覆盖的方法之外的所有内容,然后保存到 lib 中的文件并包含在 environment.rb 中.瞧,即时猴子补丁!

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!

这篇关于从 Rails 中的 gem 覆盖模块方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆