欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

7.1.3 active record callback

程序员文章站 2022-07-12 22:56:53
...

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!!!