Several methods in rails take a hash of options as the last argument. If you are passing the same options to several methods, you can remove this duplication by using with_options. Learn all about it in this episode.
# models/user.rb
with_options :if => :should_validate_password? do |user|
user.validates_presence_of :password
user.validates_confirmation_of :password
user.validates_format_of :password, :with => /^[^\s]+$/
end
attr_accessor :updating_password
def should_validate_password?
updating_password || new_record?
end
# routes.rb
map.with_options :controller => 'sessions' do |sessions|
sessions.login 'login', :action => 'new'
sessions.logout 'logout', :action => 'destroy'
end
本篇介绍Rails中如何使用with_options方法减少重复代码,通过示例展示了如何在models和routes中应用该方法来统一设置。
3800

被折叠的 条评论
为什么被折叠?



