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
Create module file in app/controllers/concerns/
Declare Concern with extend ActiveSupport::Concern
Configure before_action, helper_method etc. in included block
Use with include ModuleName in Controller
Define class methods with class_methods block
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