LoginSignup
3

More than 5 years have passed since last update.

concern内で共通化したいメソッドを定義する

Posted at

Concern Abc(abc.rb) と Concern Xyz(xyz.rb) があって、どっちからも参照したいメソッドを一つのファイルにまとめたいときはmoduleを一つ定義して両者にincludeするといいっぽい。

concerns/
  |
  +--abc.rb  <--
  |             |--どっちからも使いたいメソッドがある
  +--xyz.rb  <--
  |
  +--helper.rb
concerns/helper.rb
module Helper
  def hoge_helper
  end
end
concerns/abc.rb
module Abc
  extend ActiveSupport::Concern
  include Helper
  included do
    def abc_method
      hoge_helper # <- helper.rb に定義されている hoge_helper が使える
    end
  end
end
concerns/xyz.rb
module Abc
  extend ActiveSupport::Concern
  include Helper
  # 略
  # こちらからも helper.rb に定義されている hoge_helper が使える

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
3