开发者

Rails authentication \ Simple Ruby question

This might seem really simple, but I'm a bit confused

Here's some simple authentication code:

def self.authenticate(username="", password="")
    user = AdminUser.find_by_username(username)

    i开发者_StackOverflow社区f user && user.password_match?(password)
        return user
    else
        return false
    end
end

def password_match? (password)
    hashed_password == AdminUser.hash_with_salt(password, salt)
end

My question is, in def password_match?, how does it have access to what's inside the user object? Because user calls it? So if it said "hashed_pwd" instead of "hashed_password" it wouldn't work?


You are missing the surrounding class that this belongs to. Presumably it belongs in a User class:

class User
  def self.authenticate(username="", password="")
    user = AdminUser.find_by_username(username)

    if user && user.password_match?(password)
        return user
    else
        return false
    end
  end

  def password_match? (password)
    hashed_password == AdminUser.hash_with_salt(password, salt)
  end
end

And so yes, it is a method on that class.

user = User.authenticate("joe","12345")

user.password_match?("12345")

Notice how one is called one the class, and one is called on the object instantiated from that class.

As Paul mentioned, it is a shortcut for self.hashed_password ... But you can get into trouble using that shortcut, especially when assigning to it - hashed_password = "..." in this case, ruby may not know whether it is a method or a variable, and it may assign the value to a local variable instead of calling the hashed_password=() method as you may expect. Always use self.hashed_password=() when assigning to an attribute. :)


yes you are basically right, because that is really just shorthand for

self.hashed_password == hashed_password == Admin....

so anything else wouldn't work

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜