ruk·si

🛤️ Ruby on Rails
Concerns

Updated at 2015-09-06 02:39

Concerns are a way to group common functionality between models/controllers or split a big entity into manageable chunks.

# app/models/concerns/foobarable.rb
module Foobarable
  extend ActiveSupport::Concern

  # what happens to the model when included
  # can define references etc.
  included do
    scope :long_email, -> { where("length(email) > 10") }
  end

  # adding class method
  class_methods do
    def find_ruksi
      find_by_email("me@ruk.si") # implicit `self`
    end
  end

  # adding instance method
  def gimme_the_name
    "THE NAME IS #{name.upcase}" # implicit `self`
  end

end
# app/models/user.rb
class User < ActiveRecord::Base
  include Foobarable
  # ...
end
# usage:
User.long_email                 # use the new scope
User.find_ruksi.gimme_the_name  # get a single instance and use it

Define concerns inside directories made for them.

/app/controllers/concerns
/app/models/concerns

Concern names should always end with able. To signify that they add functionality.

Taggable
Commentable
Attendable
Trashable
Subscribable

Concerns can include other concerns.

module Fooable
  extend ActiveSupport::Concern
  # ...
end
module Foobarable
  extend ActiveSupport::Concern
  include Fooable
  # ...
end
class User < ActiveRecord::Base
  include Foobarable
  # ...
end

Sources