05 Jun 2009, 18:43
Generic-user-small

Dhana Shunmugasundram (1 post)

I am currently on page 183 on the pdf version and I am a little confused about this method. Looks like this is an instance method and not a class method, but why is the salt and encrypted_password need the self keyword in front of it. Would really appreciate it if someone could give me an idea what’s actually happening.

def encrypt_password
  return if password.blank?
  if new_record?
    self.salt = Digest::SHA1.hexdigest("--#{Time.now}--#{email}--" )
  end
  self.encrypted_password = User.encrypt(password, salt)
end
06 Jun 2009, 02:40
Derek_pragsmall

Derek DeVries (18 posts)

Dhana,

The @encrypt_password@ method is indeed an instance method. In Ruby, the keyword @self@ refers to the current object. This is similar to calling @$this->salt = …@ in PHP. Much of the time in Ruby, we don’t need to prefix the method with @self.@ because @self@ is implied. In this very method we refer to the @email@ method without using the @self.@ prefix, and Ruby implicitly knows to check instance methods for the value of @email@.

The difference is that in the case of @self.salt = … @ and @self.encrypted_password = …@, we’re assigning a variable. In this case Ruby doesn’t know if we want to set the local variable @salt@ or the @salt@ method on the current User object. The only way to let Ruby know that we want to assign the User’s @salt@ method is to explicitly use @self.salt = …@ to do so.

The @self@ keyword is used in the context of both classes and objects because classes are in fact objects themselves in Ruby.

Here is an article that explains @self@ a little better: http://rubylearning.com/satishtalim/ruby_self.html

Hope this helps! Derek

  You must be logged in to comment