2013年9月11日水曜日

[Rails]moduleの作り方とcontrollerからの呼び出し方

moduleを作って使うための方法を簡単に書きます。

1.application.rbの編集
2.moduleを作成
3.コントローラー内でmoduleの呼び出し

いってみましょう!

1.config/application.rb


libの下層の中をautoloadされるように追加

    # Custom directories with classes and modules you want to be autoloadable.
    # config.autoload_paths += %W(#{config.root}/extras)
    config.autoload_paths += %W(#{config.root}/lib)  #追加
    config.autoload_paths += Dir["#{config.root}/lib/**/"]  #追加



2.moduleを作成

lib/の中にディレクトリを作成します(ここでは"sin") その中に、rate.rbを作成します。

#coding: utf-8
module Sin
  class Rate
    def other_rate
      other_rate = "success!"
      other_rate
    end
  end
end



3.コントローラー内でmoduleの呼び出し



#coding: utf-8
class HomeController < ApplicationController
  require "sin/rate"  #追加
  include Sin  #追加
  def index
    @success = OtherRate.rate  #@success == "success!"が入ってます
  end
end


とまあ、こんな感じです!