How to define and use Rails Concerns
Ian Kamau
Posted on October 9, 2024
A Concern is a module that you extract to split the implementation of a class or module instead of having a big class body.
A Rails concern is just a plain Ruby module that extends the ActiveSupport::Concern
module provided by Rails.
Key Characteristics of Concerns:
Modularity: Concerns break down complex classes into similar, more focused units, improving code readability and understanding.
Reusability: A concern can be reused across multiple classes, reducing code duplication and promoting DRY principle.
Maintainability: Concerns can be easily extended or customized to fit specific use cases, offering flexibility and adaptability.
Testing: Concerns can be tested independently, ensuring their correctness and reliability.
Creating a concern:
Create a new Ruby module file in your
app/controllers/concerns
Extend the
ActiveSupport::Concern
module to make it a Rails concern.Define methods or class methods that encapsulates the desired functionality
Use the
included
block to automatically include the concern's methods in classes that include it.
Example
# app/controllers/concerns/searchable.rb
module Searchable
extend ActiveSupport::Concern
included do
scope :search, ->(query) { where("name ILIKE ?", "%#{query}%") }
end
end
Example using a Concern:
class Product < ApplicationRecord
include Searchable
end
Posted on October 9, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 29, 2024