0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Rails】ActiveSupport::Concern

Posted at

はじめに

ActiveSupport::Concernについて調べた内容をまとめます。

Concern

  • ModelやControllerのコードを分割(=モジュール化)するときに使えるモジュール
  • ModelやControllerとは分離させて実装でき、複数のModelやControllerで再利用することができる

ActiveSupport::Concern

  • Concenを実装するためのモジュール
  • extendして使用する

定義方法

  • app/controllers配下もしくはapp/models配下にconcernsディレクトリを作成し、ファイルを配置する
  • Concern(モジュール)をつくる
  • ActiveSupport::Concern を extend する
  • 作成した Concern (モジュール)をinclude したいクラスへ include することでそのクラス内で使用することができるようになる

実装例①(Controller)

app/controllers/concerns/current_hoge.rb
require "active_support/concern"

module CurrentHoge
  extend ActiveSupport::Concern

  included do
    helper_method :current_hoge
  end

  private

  def current_hoge
    return false unless user_signed_in?
    current_user.try(:hoge)
  end
end
app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  include CurrentHoge
end

実装例②(Model)

app/models/concerns/common_scope.rb
require "active_support/concern"

module CommonScope
  extend ActiveSupport::Concern

  included do
    scope :disabled, -> { where(disabled: true) }
  end
end
app/models/common_space.rb
class Hoge < ApplicationRecord
  include CommonScope
end

included メソッド

  • ActiveSupport::Concernをextendすると使用できる
  • includeした際に呼び出されるコールバックメソッド
  • クラスでモジュールをincludeすると、モジュール内で定義されたincludedメソッドを自動的に呼び出す

参考

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?