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
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 thePasswordclass. Thus the difference:StringvsPassword. You can call methods such ascost,versionetc. on thePasswordobject, which are unavailable forString.I guess you find the following method strange:
but what happens here, which is not obvious is the conversion of the
Passwordobject toStringobject in theself.password_hashassignment – theto_smethod returns the hash of the password and that value is stored in the database. What is more – the@passwordinstance variable is set, so thepasswordmethod will return an instance ofPasswordclass, not the password hashString.