原创作者: hideto   阅读:1258次   评论:0条   更新时间:2011-05-26    
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
评论 共 0 条 请登录后发表评论

发表评论

您还没有登录,请您登录后再发表评论

文章信息

Global site tag (gtag.js) - Google Analytics