How to define and use Rails Concerns

iankcode

Ian Kamau

Posted on October 9, 2024

How to define and use Rails Concerns

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:

  1. Create a new Ruby module file in your app/controllers/concerns

  2. Extend the ActiveSupport::Concern module to make it a Rails concern.

  3. Define methods or class methods that encapsulates the desired functionality

  4. 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
Enter fullscreen mode Exit fullscreen mode

Example using a Concern:

class Product < ApplicationRecord
  include Searchable
end
Enter fullscreen mode Exit fullscreen mode
đź’– đź’Ş đź™… đźš©
iankcode
Ian Kamau

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