chapter 7.2.4
1. we need to create a user, save it to database
2. we need to get the user object by email
3. we need to verify that it has a given password
not surprising, we will start from test again, right, TDD!!!!!
we expect we will have a class method:
User.authenticate(email, submitted_password)
it should return nil if email/password combination is invalid
it should return nil if no user exists with the given email
it should return the user object itself on success.
from this points, we can write the test:
describe "authenticate method" do
it "should return nil on email/password mismatch" do
wrong_password_user = User.authenticate(@attr[:email], "wrongpasss")
end
it "should return nil for an email address with no user" do
nonexistent_user = User.authenticate("bar@foo.com", @attr[:password])
end
it "should return the user on email/password match" do
matching_user = User.authenticate(@attr[:email], @attr[:password])
matching_user.should == @user
end
end
(for a class method, when using inside the class definition, we can omit the class name)
now it is the turn of authenticate method definition:
def self.authenticate(email, submitted_password)
user = find_by_email(email)
return nil if user.nil?
return user if user.has_password?(submitted_password)
end
note, since find_by_email class method is called inside the class, the class name can be omitte.
the method will return the value of the last statement.
2. what is self?
a. inside the method definition, self means the object itself.
b. when define a class method, self means the Class itself.
def self.authenticate
end
c. another way to define a class method:
def User.authenticate
end
d. another way to defind a class method
class << self
def authenticate
end
end
the last way of definition is very weird, you don't need to use it by yourself, but you need to know it, in case you come across it when others' codes.