Ahmad Al-kheat
Ahmad Al-kheat

Reputation: 1795

Rails callback not using self

Code snippet from Rails Guides :

class User < ActiveRecord::Base
      before_validation :normalize_name, on: :create

      protected
        def normalize_name
          self.name = self.name.downcase.titleize
        end
    end

Why did we use self.name in the right side of the statement? Can't we say

self.name = name.downcase.titleize

Upvotes: 1

Views: 279

Answers (2)

markets
markets

Reputation: 7033

It seems a community convention to use self only when using write accessors.

# writer
self.name=

# reader
name

Defined in: https://github.com/bbatsov/ruby-style-guide#no-self-unless-required.

Example from guide:

# bad
def ready?
  if self.last_reviewed_at > self.last_updated_at
    self.worker.update(self.content, self.options)
    self.status = :in_progress
  end

  self.status == :verified
end

# good
def ready?
  if last_reviewed_at > last_updated_at
    worker.update(content, options)
    self.status = :in_progress
  end

  status == :verified
end

Upvotes: 2

Noel Frostpaw
Noel Frostpaw

Reputation: 3999

You can, but it could make code unreadable or lead to ambiguity. It's more clear to use self.name on both sides so everyone reading your code knows what happens.

I've done a small example using IRB to illustrate what happens:

2.1.5 :014 > class User
2.1.5 :015?>   attr_accessor :name
2.1.5 :016?>   def normalize_name
2.1.5 :017?>     self.name = name.downcase
2.1.5 :018?>     end
2.1.5 :019?>   end
 => :normalize_name 
2.1.5 :020 > u = User.new
 => #<User:0x007ff81282a070> 
2.1.5 :021 > u.name = "NAME"
 => "NAME" 
2.1.5 :022 > u.normalize_name
 => "name" 
2.1.5 :023 > 

So yes, you can do it. But it's cleaner to use self.name so there's no ambiguity.

Upvotes: 1

Related Questions