在Rails中从一个gem重写一个模块方法 [英] Overriding a module method from a gem in Rails

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

问题描述

will_paginate gem在我的Oracle版本中被破坏了。 WillPaginate模块中的默认 paginate_by_sql 方法会在查询中插入一个额外的'AS'并导致其失败。



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



我不想更改gem本身的代码,因为这会让我的代码在其他机器上崩溃。



我试着创建一个包含以下内容的lib / test.rb文件:

  module WillPaginate 
def paginate_by_sql
(我的代码放在这里)
end
end

,并且从environment.rb中获取它,但它没有提取我的更改。
我也尝试过从controllers / application.rb中请求它,但是再次没有收到我的修改。



暂时,我通过覆盖方法在特定的模型本身,但这是一个黑客,并且意味着我不能使用它在这个项目的任何其他模型中。



我我确信有一个简单的方法可以做到这一点,但我没有任何运气使用Google进行追踪。

你在做什么都可以,但你的代码需要如下所示:

  module WillPaginate 
module Finder
module ClassMethods $ b $ def def paginate_by_sql(sql,options)
#您的代码在这里
end
end
end
end

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

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.

解决方案

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!

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

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