Friday, May 9, 2025
News PouroverAI
Visit PourOver.AI
No Result
View All Result
  • Home
  • AI Tech
  • Business
  • Blockchain
  • Data Science & ML
  • Cloud & Programming
  • Automation
  • Front-Tech
  • Marketing
  • Home
  • AI Tech
  • Business
  • Blockchain
  • Data Science & ML
  • Cloud & Programming
  • Automation
  • Front-Tech
  • Marketing
News PouroverAI
No Result
View All Result

How to organize your code using Rails Concerns

November 2, 2023
in Front-Tech
Reading Time: 4 mins read
0 0
A A
0
Share on FacebookShare on Twitter



There is a strong chance you’ve encountered Rails Concerns if you’ve been using Rails for a while. It can be confusing to understand where it fits into your Rails application and how best to make use of it. This is what we’ll be covering in this tutorial: what Rails Concerns are, why they exist, and their use cases.

What are Rails Concerns? In simple terms, a concern is a module. First, let’s review what a module is. A module is a collection of methods, constants, and class variables. Typically, modules can be used for two things: To share functionality across multiple places, such as classes; As namespaces. For our use case, we’ll focus on sharing functionality across multiple places. You do this by including the module in the places where you need such functionalities. You can think of a module as a bucket of related behaviors (methods) or data (attributes). These behaviors and attributes can then be used across different classes (or modules).

Here is what a concern looks like:

<pre>require "active_support/concern"
module M
  extend ActiveSupport::Concern

  included do
    scope :disabled, -> { where(disabled: true) }
  end

  class_methods do
    ...
  end
end</pre>

If we’re writing an equivalent without using Rails concern, ActiveSupport::Concern, it will look like this:

<pre>module M
  def self.included(base)
    base.extend ClassMethods
    base.class_eval do
      scope :disabled, -> { where(disabled: true) }
    end
  end

  module ClassMethods
    ...
  end
end</pre>

In the code above, you can see that Rails Concern gives us a cleaner interface to work with. You can also see that we have what looks like a block: included and class_methods. class_methods in the concern defines class methods that will be available on the including class. These methods can be accessed on the class itself, rather than on instances of the class. included is a callback method that allows you to include code as if it were written directly in the including class. It gives you the ability to modify the class itself when the concern is included. It’s as if the code inside the included block has been pasted into the class where the concern is included.

Why do they exist? When we say a concern is a module, it means that, like a module, a concern makes it possible to share functionality across different classes in a Rails application. Here is a snippet from Rails Guides: Concerns are a way to make large controllers or models easier to understand and manage. This also has the advantage of reusability when multiple models (or controllers) share the same concerns. Concerns are implemented using modules that contain methods representing a well-defined slice of the functionality that a model or controller is responsible for. In other languages, modules are often known as mixins. If you have a piece of code that is used in different places in your code base, it will be helpful to abstract it into a concern.

Let’s say I have different scopes that I use in different models:

<pre>scope :created, -> { where(status: 'created') }
scope :updated, -> { where(status: 'updated') }
scope :deleted, -> { where(status: 'deleted') }
scope :from_date, ->(date) { where(T.unsafe(arel_table)[:created_at].gteq(date)) }
scope :to_date, ->(date) { where(arel_table[:created_at].lteq(date)) }</pre>

I can move that into a concern, which I can then use across the models involved. When should you use them? As mentioned above, you can use Rails Concerns when handling code reusability. It’s also common to make use of it for things like validation and error handling. For example, you can have an error handler like this:

<pre>module ErrorHandlerConcern
  extend ActiveSupport::Concern

  included do
    rescue_from(Unauthorized) do |exception|
      render json: { errors: "Unauthorized" }, status: 401
    end

    rescue_from(UnprocessableEntity) do |exception|
      render json: { errors: "Unprocessable Entity" }, status: 422
    end

    rescue_from(BadRequest) do |exception|
      render json: { errors: "There's something wrong with your request" }, status: 400
    end

    rescue_from(Forbidden) do |_exception|
      render json: { errors: "You are not allowed" }, status: 403
    end

    rescue_from(ActiveRecord::RecordNotFound) do |_exception|
      render json: { errors: "Record not found" }, status: 404
    end
  end
end</pre>

The code snippet above creates an error handler that rescues from certain errors. The rescue blocks are in the included block. This can then be included in the ApplicationController since this is something I’ll want to make use of across my application. The same applies to validations or authorization.

How should you use them? By default, the Rails application comes with a directory for concerns. You’ll see this in the controllers and models directories. Thus, you’ll want to place concerns that are related to models in app/models/concerns and that of controllers in app/controllers/concerns.

In one of my projects, I have a concern called VersionConcern that looks like this:

<pre>module VersionConcern
  extend ActiveSupport::Concern

  included do
    scope :active, -> { where(deleted_at: nil) }
    scope :deleted, -> { where.not(deleted_at: nil) }
  end

  class_methods do
    def delete_all_records
      update_all(deleted_at: Time.current)
    end

    def restore_all_records
      update_all(deleted_at: nil)
    end
  end
end</pre>

This concern makes it possible for me to scope records based on whether they are active or deleted. To make use of this in a book model, I only need to include the concern in the model like this:

<pre>class Book < ApplicationRecord
  include VersionConcern
  belongs_to :author, class_name: 'User', foreign_key: 'user_id'
  ...
end</pre>

If I want to fetch the active books for a user, I can do this:

<pre>Books.find_by(author_id: current_user.id).active</pre>

We can also make use of the class methods like so; Book.delete_all_records.

Pitfalls While Rails concerns help with reducing duplication, it is not the only “tool” out there. You can also create a service that holds this common code. It is important to know that Concerns are inheritance. Therefore, for example, if you check the lookup path of .active methods, you’ll see that VersionConcern is included. If you are concerned about that, you might want to consider something else, like making use of a service. Concerns are, however, a helpful tool to have in your Rails toolkit.

Conclusion While you might not necessarily use Concerns every time, it’s important to know what they do. In this tutorial, we’ve learned about the similarity between concerns and modules, why we have them, and how we can use them.



Source link

Tags: CodeconcernsorganizeRails
Previous Post

6 Ways to Use Data to Improve Employee Productivity

Next Post

Software Engineer Ranks Programming Languages

Related Posts

The essential principles of a good homepage
Front-Tech

The essential principles of a good homepage

June 7, 2024
How to measure and improve user retention
Front-Tech

How to measure and improve user retention

June 6, 2024
Push Animation on Grid Items
Front-Tech

Push Animation on Grid Items

June 5, 2024
How to build a Rails API with rate limiting
Front-Tech

How to build a Rails API with rate limiting

June 4, 2024
Introduction to the B.I.A.S. framework
Front-Tech

Introduction to the B.I.A.S. framework

June 3, 2024
Blue Ridge Ruby is exactly what we need
Front-Tech

Blue Ridge Ruby is exactly what we need

June 3, 2024
Next Post
Software Engineer Ranks Programming Languages

Software Engineer Ranks Programming Languages

First Trade: Zee Business Live | Share Market Live Updates | Stock Market News | 27th October 2023

First Trade: Zee Business Live | Share Market Live Updates | Stock Market News | 27th October 2023

Gary Gensler DESTROYED By Congress!🔥FULL RECAP🔥 Crypto vs SEC

Gary Gensler DESTROYED By Congress!🔥FULL RECAP🔥 Crypto vs SEC

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

  • Trending
  • Comments
  • Latest
Is C.AI Down? Here Is What To Do Now

Is C.AI Down? Here Is What To Do Now

January 10, 2024
Porfo: Revolutionizing the Crypto Wallet Landscape

Porfo: Revolutionizing the Crypto Wallet Landscape

October 9, 2023
A Complete Guide to BERT with Code | by Bradney Smith | May, 2024

A Complete Guide to BERT with Code | by Bradney Smith | May, 2024

May 19, 2024
A faster, better way to prevent an AI chatbot from giving toxic responses | MIT News

A faster, better way to prevent an AI chatbot from giving toxic responses | MIT News

April 10, 2024
Part 1: ABAP RESTful Application Programming Model (RAP) – Introduction

Part 1: ABAP RESTful Application Programming Model (RAP) – Introduction

November 20, 2023
Saginaw HMI Enclosures and Suspension Arm Systems from AutomationDirect – Library.Automationdirect.com

Saginaw HMI Enclosures and Suspension Arm Systems from AutomationDirect – Library.Automationdirect.com

December 6, 2023
Can You Guess What Percentage Of Their Wealth The Rich Keep In Cash?

Can You Guess What Percentage Of Their Wealth The Rich Keep In Cash?

June 10, 2024
AI Compared: Which Assistant Is the Best?

AI Compared: Which Assistant Is the Best?

June 10, 2024
How insurance companies can use synthetic data to fight bias

How insurance companies can use synthetic data to fight bias

June 10, 2024
5 SLA metrics you should be monitoring

5 SLA metrics you should be monitoring

June 10, 2024
From Low-Level to High-Level Tasks: Scaling Fine-Tuning with the ANDROIDCONTROL Dataset

From Low-Level to High-Level Tasks: Scaling Fine-Tuning with the ANDROIDCONTROL Dataset

June 10, 2024
UGRO Capital: Targeting to hit milestone of Rs 20,000 cr loan book in 8-10 quarters: Shachindra Nath

UGRO Capital: Targeting to hit milestone of Rs 20,000 cr loan book in 8-10 quarters: Shachindra Nath

June 10, 2024
Facebook Twitter LinkedIn Pinterest RSS
News PouroverAI

The latest news and updates about the AI Technology and Latest Tech Updates around the world... PouroverAI keeps you in the loop.

CATEGORIES

  • AI Technology
  • Automation
  • Blockchain
  • Business
  • Cloud & Programming
  • Data Science & ML
  • Digital Marketing
  • Front-Tech
  • Uncategorized

SITEMAP

  • Disclaimer
  • Privacy Policy
  • DMCA
  • Cookie Privacy Policy
  • Terms and Conditions
  • Contact us

Copyright © 2023 PouroverAI News.
PouroverAI News

No Result
View All Result
  • Home
  • AI Tech
  • Business
  • Blockchain
  • Data Science & ML
  • Cloud & Programming
  • Automation
  • Front-Tech
  • Marketing

Copyright © 2023 PouroverAI News.
PouroverAI News

Welcome Back!

Login to your account below

Forgotten Password? Sign Up

Create New Account!

Fill the forms bellow to register

All fields are required. Log In

Retrieve your password

Please enter your username or email address to reset your password.

Log In