LoginSignup
346

More than 5 years have passed since last update.

長くなりがちなRailsのモデルをきれいに分割する

Last updated at Posted at 2013-01-14

FrogApps 技術ブログ始めました!
RailsやiOS、HTML5の情報を発信中!! → http://qiita.com/teams/frogapps


Railsでアプリを作っていると、app/models/以下にあるモデルファイルの行数が非常に長くなることになります。

そこでincludeメソッドを使ってモデルファイルを機能毎に分割してみましょう。

ファインダー関係のメソッドだけを、user/finder.rbに切り出します。
このときクラスメソッド関係は通常の定義方法が異なります。

クラスメソッドの定義は、ClassMethodsモジュールの中で行う様にします。

has_many, belongs_toなどのクラスメソッドの実行は、self.includedの中でbase.has_manyの様にして呼び出します。

app/models/user.rb
class User < ActiveRecord::Base
   include User::Finder
end
app/models/user/finder.rb
module User::Finder
  def self.included(base)
    base.extend ClassMethods

    # クラスメソッドの呼び出し
    base.has_many :items
  end

  # クラスメソッドの定義
  module ClassMethods
    def hot
      ...
    end
  end

  # インスタンスメソッドの定義
  def search(str)
    ...
  end
end

このようにしてファイルを分けることで、モデルファイルが大きくなるのを避けられ機能毎に整理することができます。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
346