๐Ÿงฉ

Controller Concerns

Modules shared across multiple Controllers

Concerns are a module pattern using Ruby's ActiveSupport::Concern, used to share common functionality across multiple Controllers (or Models).

# app/controllers/concerns/paginatable.rb
module Paginatable
  extend ActiveSupport::Concern

  included do
    helper_method :page, :per_page
  end

  private

  def page
    (params[:page] || 1).to_i
  end

  def per_page
    (params[:per_page] || 20).to_i
  end

  def paginate(scope)
    scope.offset((page - 1) * per_page).limit(per_page)
  end
end

Usage: include Paginatable

included block: Executes at include time (before_action, helper_method, etc.)
class_methods block: Defines class methods

Concerns are ideal for cross-cutting concerns. They cleanly separate functionality like authentication, logging, and pagination that spans multiple controllers.

Key Points

1

Create module file in app/controllers/concerns/

2

Declare Concern with extend ActiveSupport::Concern

3

Configure before_action, helper_method etc. in included block

4

Use with include ModuleName in Controller

5

Define class methods with class_methods block

6

Model Concerns use the same pattern in app/models/concerns/

Pros

  • Maximize code reuse (DRY)
  • Controller/Model files stay clean
  • Leverages Ruby module system โ†’ easy to test
  • Structured with included/class_methods

Cons

  • Overuse makes code hard to trace
  • Including multiple Concerns may cause method conflicts
  • Priority harder to understand than inheritance
  • Large Concerns should be extracted to services

Use Cases

Authentication/authorization modules Pagination Search functionality Audit logging API response formatting