Ruby Fu

Secrets of a Ruby Ninja for your edification and amusement.

Wednesday, May 30, 2007

 

Anonymous Block Pitfall

You should understand this...
a=[:x,:y,:z] # => [:x, :y, :z]
a.map{|a|} # => [nil, nil, nil]
a # => :z

...to know why this routes.rb example using with_options...
map.with_options :controller => 'users',
:action => 'show' do |map|
map.user_groups '/users/:id/groups', :section => 'groups'
map.user_history '/users/:id/history', :section => 'history'
end

...is bad.

Don't reuse the name of a local variable as a yielded local variable for use inside of a block, because the assignment will persist after the lifespan of the block. The routes example should look more like this...
map.with_options :controller => 'users',
:action => 'show' do |users|
users.user_groups '/users/:id/groups', :section => 'groups'
users.user_history '/users/:id/history', :section => 'history'
end

That is all.

Labels: , , ,


posted by Brendan Baldwin  # 1:16 PM   1 Comments   Links to this post

Archives

May 2007   June 2007  

This page is powered by Blogger. Isn't yours?

Subscribe to Posts [Atom]