#42
Jun 08, 2007

with_options

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.
Download (9 MB, 3:55)
alternative download for iPod & Apple TV (5.5 MB, 3:55)
# 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

8 comments

chineseGuy Jun 08, 2007 at 01:52

very nice!~


Alex G Jun 08, 2007 at 07:05

Good tip! Didn't know about this.


Geoff Buesing Jun 08, 2007 at 08:33

Very helpful -- thanks!


Rafael Jun 08, 2007 at 13:58

Thanks again, it is the highlight for the day, when I find a new episode.


weskycn` Jun 09, 2007 at 06:16

太好了,谢谢恁!


Ben Jun 09, 2007 at 14:39

Hey, great job on the screencast. I love watching your tips and tricks. One thing I have a question about though. Not to do with Rails, but rather Textmate. I noticed about 3/4 into the cast, that you selected "map." on two different lines, and then were able to edit both lines simultaneously... My jaw dropped on that one. Could you explain how you did that?


Ryan Bates Jun 09, 2007 at 18:30

@Ben, the trick is to hold down the "option" key while you make a selection in textmate. This will switch it to column mode and allow you to edit multiple lines at once. After you make a selection you can hit "option" again to toggle back and forth. It's pretty useful. :)


kino May 10, 2008 at 08:04

This was new for me. It's amazing at how well thought out rails is.

Thanks again for the video Ryan.

Add your comment:

(SKIP THIS ONE)

(required)

(not shown)


(required)

subscribe:
sponsored by:
if you want to help:
required:
Get Quicktime Player