small medium large xlarge

13 Jan 2008, 20:38
Barry Simpson (1 post)

I need some clarification on page 157 (2nd edition) – probably because I’m a newbie to both Ruby and Rails.

In the create_new_salt method, why wouldn’t you use @salt instead of self.salt? Don’t those mean the same thing? The text says you wouldn’t want to use salt = because Ruby would think you were referring to a local variable. That much is obvious to me already. But why wouldn’t you use @salt = , like most other places in the book, to assign to the instance variable?

Loving the book, by the way.

17 Jan 2008, 00:22
Russell Healy (2 posts)

I suppose that @self.salt = …@ is used so that the method generated by rails is called, rather than assigning to the instance variable, which would be making an assumption about the rails implementation. In fact, if you inspect the user (with user.inspect) you will see that rails doesn’t even create an instance variable called @salt. Instead, all of the attributes generated by inspecting the database schema are put in a hash called attributes:

<User:0xb69384cc @attributes={“salt”=>”123”, “name”=>”benjamin”, “hashed_password”=>”a335e63a110911315788dbe5b1d44815bdd528ae”, “id”=>2}

The accessor method ‘salt’ must retrieve the value from the @attributes hash.

That doesn’t explain though, the use of self.password and self.salt in the line on page 158:

self.hashed_password = User.encrypted_password(self.password, self.salt)

The following should be sufficient:

self.hashed_password = User.encrypted_password(password, salt)
17 Jan 2008, 00:25
Russell Healy (2 posts)

Ugh, sorry about the formatting. I wish this forum had a preview!

24 Feb 2008, 07:33
Paul Jewell (2 posts)

It doesn’t have preview, but it does allow you to edit the post. I had the same thought posting a message in a different area, but luckily spotted the edit button next to the avatar :-)

You must be logged in to comment