write a authenticate method

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值