Local Variable in Method

I came across the following code in Agile Dev with Rails 4th Edition

def password=(password)
@password = password

if password.present?
generate_salt
self.hashed_password = self.class.encrypt_password(password, salt)
end
end

And I was very confused regarding the “salt” part in
“encrypt_password(password,salt)”

Isn’t “salt” an undefined local variable???
What’s going on here?

Here’s the code for the entire class, taken from the official website

#—

Excerpted from “Agile Web D. with Rails, 4rd Ed.”,

published by The Pragmatic Bookshelf.

Copyrights apply to this code. It may not be used to create training

material,

courses, books, articles, and the like. Contact us if you are in

doubt.

We make no guarantees that this code is fit for any purpose.

Visit http://www.pragmaticprogrammer.com/titles/rails4 for more book

information.
#—
require ‘digest/sha2’

class User < ActiveRecord::Base
validates :name, :presence => true, :uniqueness => true
validates :password, :confirmation => true

attr_accessor :password_confirmation
attr_reader :password

validate :password_must_be_present

def User.authenticate(name, password)
if user = find_by_name(name)
if user.hashed_password == encrypt_password(password, user.salt)
user
end
end
end

def User.encrypt_password(password, salt)
Digest::SHA2.hexdigest(password + “wibble” + salt)
end

‘password’ is a virtual attribute

def password=(password)
@password = password

if password.present?
  generate_salt
  self.hashed_password = self.class.encrypt_password(password, salt)
end

end

private

def password_must_be_present
  errors.add(:password, "Missing password") unless

hashed_password.present?
end

def generate_salt
  self.salt = self.object_id.to_s + rand.to_s
end

end

Max Y. wrote in post #1002139:

def generate_salt
  self.salt = self.object_id.to_s + rand.to_s
end

end

My guess is that salt is an attribute of the User model and stored in
the database column of the same name. That database column would be
accessed through the dynamically generated salt method.

WOW thanks, now everything makes sense

I wish the book explains stuff like this…so confusing if the reader
is a beginner…and beginners are the book’s target audience…

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs