应该在哪里放置ActiveRecord扩展模块?

时间:2014-07-03 22:36:05

标签: ruby-on-rails ruby ruby-on-rails-4

我有这个模块:

class ActiveRecord::Base
 class << self
  def has_simple_search(*attrs)
   raise 'has_simple_search expects at least one attribute' if attrs.empty?
    instance_eval do # because this is ActiveRecord::Base, the class inherits this
     class_attribute :simple_search_fields
     self.simple_search_fields = attrs.flatten
     def simple_search(search_string)
      return find(:all) if search_string.nil? || search_string.blank?
      attrs = self.simple_search_fields
      like_s = attrs.map{|f| "#{self.table_name}.#{f.to_s} REGEXP ?"}.join(' OR ')
      terms = search_string.split(' ').map{|s| Regexp.escape(s.strip)}
      where(Array.new(attrs.count, terms.join('|')).unshift(like_s))
     end
    end
   end
  end
end

https://gist.github.com/Florian95/2478919

我试图在我的Rails应用程序中实现它,但我无法找到我应该放在哪里。

另外:此代码是否可重复用于rails 4?

1 个答案:

答案 0 :(得分:-1)

您应该将其放入config/initializers

我真的不知道它是否可以在Rails 4上重复使用,试试看。