Thiem Nguyen
Thiem Nguyen

Reputation: 6365

Differences between 2 ways of Rails module included callbacks?

I'm new to Rails. I have a model called AdvItem, basically what I want to do is to move all its validation statements to a module named AdvItemValidation. After some searches here's what I get:

module AdvItemValidation
  extend ActiveSupport::Concern

  included do
    # validations
    validates :link, presence: true
    validate :check_valid_link
  end

  def check_valid_link
    ...
  end
end

But I've just seen another way to do this:

module AdvItemValidation
  extend ActiveSupport::Concern

  def self.included(base)
    # validations
    base.validates :link, presence: true
    base.validate :check_valid_link
  end

  def check_valid_link
    ...
  end
end

So what is the difference between these 2 ways of implementation? And which way is better providing that I have a lot of default and custom validation statements?

PS: For the 1st way CodeClimate reports this message "Very complex code in AdvItemValidation definition outside of methods", but imho I see it much shorter.

Thanks for the explanations.

Upvotes: 1

Views: 309

Answers (2)

coderhs
coderhs

Reputation: 4857

Well the second code snippet is ruby ruby code.

  def self.included(base)
    # validations
    base.validates :link, presence: true
    base.validate :check_valid_link
  end

It has no dependency on any library.

The first piece of code, has dependency on ActiveSupport so won't work without including that library.

  included do
    # validations
    validates :link, presence: true
    validate :check_valid_link
  end

Upvotes: 1

Montdidier
Montdidier

Reputation: 1210

The form below

def self.included(base)

is the default callback called when a module is included in another module and class.

The other form

included do

is provided by ActiveSupport::Concern

If you are using active support and Concerns you should preference this form. If not you will be limited to the first form anyway.

The include from Concern is largely syntactic sugar, although it does handle dependencies more gracefully.

Some further explanation here http://api.rubyonrails.org/classes/ActiveSupport/Concern.html

Upvotes: 1

Related Questions