モジュールでnamed_scopeを追加

モデルの機能ごとにモジュールにまとめてあとからまとめてincludeしたいというときに、どうせならその機能のために用意したちょっと複雑なnamed_scopeも同じように外に出してしまいたい。

そんな場合にはincludedとclass_evalを使う。

class Message < ActiveRecord::Base
  include Extensions::Search
end

module Extensions
  module Search
    def self.included(mod)
      mod.class_eval do
        named_scope :name_like, lambda { |arg| {
          :conditions => ["name LIKE ?", "%%arg%%"]
        }}
      end
    end
  end
end
> Message.name_like("ob").first.name #=> "Bob"

named_scopeも結局はクラスメソッド。この方法はnamed_scope以外にも利用できる。


Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <img localsrc="" alt="">