诗歌rails 之with_options

Rails里有些方法使用一个Hash作为最后一个可选的参数,如果对多个方法有同样的选项,我们可以使用with_options来减少冗余:
ruby代码
  1. # models/user.rb  
  2. with_options :if => :should_validate_password? do |user|  
  3.   user.validates_presence_of :password  
  4.   user.validates_confirmation_for :password  
  5.   user.validates_format_of :password, :with => /^[^\s]+$/  
  6. end  
  7.   
  8. attr accessor :updating_password  
  9.   
  10. def should_validate_password?  
  11.   updating_password || new_record?  
  12. end  
  13.   
  14. # routes.rb  
  15. map.with_options :controller => 'sessions' do |sessions|  
  16.   sessions.login 'login', :action => 'new'  
  17.   sessions.logout 'logout', :action => 'destroy'  
  18. end  
posted @ 2009-07-09 10:01  麦飞  阅读(341)  评论(0编辑  收藏  举报