author avatar

nived.hari

Thu Oct 24 2024

Concerns
A Rails concern is just a plain Ruby module that extends the ActiveSupport::Concern module provided by Rails.
They help in organizing and reusing code across controllers and models by extracting common functionality into modules.


There are 2 main blocks in a concern

1. included

1. Any code inside this block is evaluated in the context of the including class.
2. if sample class includes a concern, anything inside the included block will be evaluated as if it was written inside the sample class.
3. This block can be used to define Rails macros like validations, associations, and scopes.
4. Any method you create here becomes instance methods of the including class.
2. class_methods

1. Any methods that you add here become class methods on the including class.
Example:

typically concerns are located in app/controllers/concerns or app/models/concerns


module ExampleConcern
  extend ActiveSupport::Concern

  included do
    # any code that you want inside the class
    # that includes this concern
  end

  class_methods do
    # methods that you want to create as
    # class methods on the including class
  end
end


Including this concern in a controller:



class SomeController < ApplicationController
 include ExampleConcern
end


#RubyOnRails #concerns #CU6U0R822