1

The ruby gem BCrypt has an example of how to use one of it's modules. Taken from the docs:

def password
  @password ||= Password.new(self.password_hash)
end

def password=(new_password)
  @password = Password.create(new_password)
  self.password_hash = @password
end

Why would we use the instance variable @password at all when we have the self.password_hash attribute? I feel like I am missing something, probably due to my inexperience with ruby. Personally, I would have accomplished what I believe to be the same with:

def password
  self.password_hash ||= Password.new(self.password_hash)
end

def password=(new_password)
  self.password_hash = Password.create(new_password)
end
1
  • 2
    I started to answer - but then realized, you are right, it is a bit strange. I think we'd have to investigate the surrounding context to figure out what the difference is between @password and #password_hash. I would think your method would work, but there may be other side effects that require these two to be allowed to differ, sometimes. The only thing I can tell for sure is that @password is always a Password instance, but it appears #password_hash can be, but does not appear as if it always would be. Is there an alterate way to call #password_hash=? Commented Mar 1, 2012 at 22:14

1 Answer 1

2

The difference is as follows: password hash is a string - a hash of the password. However Password.new(self.password_hash) creates new object of the Password class. Thus the difference: String vs Password. You can call methods such as cost, version etc. on the Password object, which are unavailable for String.

I guess you find the following method strange:

def password=(new_password)
  @password = Password.create(new_password)
  self.password_hash = @password
end

but what happens here, which is not obvious is the conversion of the Password object to String object in the self.password_hash assignment - the to_s method returns the hash of the password and that value is stored in the database. What is more - the @password instance variable is set, so the password method will return an instance of Password class, not the password hash String.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, that makes perfect sense. looking back at docs, it does state that self.password_hash is a :string in the database. +1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.