Sunday, March 11, 2007

Implementing predefined callback methods

Rails predefines quite a few callback and filter - methods like before_create, anticipating that you may want to perform programming actions in your application but not dictating what those actions should be. These filters are analogous to the helper-file facility: They’re a halfway measure that makes it easy for you to add the finishing touches.
Rails预先定义了很多Method Hook,当你把这个hook放到一个model class里面的时候,Rails就会执行这个hook。至于执行什么事情,决定于你在这个Method Hook里面填写上了什么东西。比如:
It might be more graceful to have a default string value for the description field. If no description exists for the edition at the time the database record is first created, let’s have it default to “standard”.
To bring this about, insert the following method definition into edition.rb (just prior to the end that ends the file):
def before_create
self.description = "standard" unless description
end
This code basically says: if description is nil, set it to “standard”.
The code is executed just before a new edition is saved to the database. Thus any edition without a description gets one.

No comments: