LoginSignup
20
21

More than 5 years have passed since last update.

Rails 3.1で「/lib/assets」に設置した共通モジュールの使い方

Last updated at Posted at 2013-01-02

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に処理をまとめるなどで対応したほうが、スマートだと思います。

20
21
0

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
20
21