Rails宝典之第四十二式: with_options

Rails里有些方法使用一个Hash作为最后一个可选的参数,如果对多个方法有同样的选项,我们可以使用with_options来减少冗余:
# models/user.rb
with_options :if => :should_validate_password? do |user|
  user.validates_presence_of :password
  user.validates_confirmation_for :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)