DEV Community

Cover image for How to define and use Rails Concerns
Ian Kamau
Ian Kamau

Posted on

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

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay