7.1.3 active record callback

chapter 7.1.3

 

now that our user model has an attr for storing password, we need to arrange to generate and save an encrypted password when save user to the database.

 

the technique of doing this is callback.

 

we will use before_save callback to create the encrypted_password.

 

1. start from test again.

 

we just need to make sure the saved encrypted password is not blank.

 

 

it "should set the encrypted password" do
    @user.encrypted_password.should_not be_blank
end

 

2. next, we will registe a callback called encrypt_password by passing a symbol of that name to before_save method.

 

 

before_save :encrypt_password

private
  def encrypt_password
    self.encrypted_password = encrypt(password)
  end

  def encrypt(string)
    string
  end

 note:

the two method are private methods, it is a good habit to have indentation for private method, which make you fastly deduce this is a private method, or you may get into trouble some time.

 

don't care the difference of private and protect, just use private is enough for you!!!!!!

 

it is a good practice to make method private unless they are needed for the public interface!!

 

These are one-line method, (the best kind!!!)

 

self refer to the object itself. it can't be omitted, or encrypted_password will be a common local variable!!!!

 

but the "password" at the right side can omit self, as it is on the right side!!!

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值