Rails3以降ではautoloadが使えなくなって、共通モジュールの配置についてまとまった説明がなかったので、実際に動かしてみました。
WEBrick再起動していなくて、キャッシュが残ってちゃんと動いてなかったので、若干requireとincludeを修正しています、、、
/lib/assets/hoge_module.rb
# -*- coding: utf-8 -*-
module Hogehoge
def test
※、処理
end
end
とした場合、まずこのモジュールをアプリ実行時に自動的に読み込むようにするため、以下の設定をします。
/config/application.rb
# Custom directories with classes and modules you want to be autoloadable.
# config.autoload_paths += %W(#{config.root}/extras)
# ※、root直下のlibディレクトリ内のファイルを自動読み込み
config.autoload_paths += %W(#{config.root}/lib)
config.autoload_paths += Dir["#{config.root}/lib/**/"]
その後、コントローラ、ヘルパー、モデルでは以下のようにして使用します。
/app/controller/application_controller.rb
# -*- coding: utf-8 -*-
require "hoge_module"
include Hogehoge
class ApplicationController < ActionController::Base
protect_from_forgery
end
/app/helper/application_helper.rb
# -*- coding: utf-8 -*-
require "hoge_module"
module ApplicationHelper
end
/app/models/hoge.rb
# -*- coding: utf-8 -*-
require "hoge_module"
class Hoge < ActiveRecord::Base
end
これが、Rails3のお作法として合っているかは微妙ですが、処理を一つのファイルにまとめられます。
最も、こうやる前に設計でmodelに処理をまとめるなどで対応したほうが、スマートだと思います。