I have this RoR snippet in a view:
<%= link_to_unless(@posts_pages[:previous].nil?,
"Previous",
blog_with_page_path(:page_num => @posts_pages[:previous])) %>
Here blog_with_page is a named route. The snippet works if @posts_pages[:previous].nil? is false (as expected) and the link is generated correctly. However, when @posts_pages[:previous].nil? is true, instead of simply getting the "Previous" string back, I get an error telling me that the route couldn’t be generated using :page_num=>nil. Is this the expected behavior? If the condition is met, the route code shouldn’t be evaluated, should it?
Here’s the complete error:
blog_with_page_url failed to generate from {:page_num=>nil, :action=>"show", :controller=>"pages"}, expected: {:action=>"show", :controller=>"pages"}, diff: {:page_num=>nil}
I’ve been looking at the link_to_unless code and I don’t understand why I get the error since it should be returning simply the name:
# File actionpack/lib/action_view/helpers/url_helper.rb, line 394
def link_to_unless(condition, name, options = {}, html_options = {}, &block)
if condition
if block_given?
block.arity <= 1 ? capture(name, &block) : capture(name, options, html_options, &block)
else
name
end
else
link_to(name, options, html_options)
end
end
I’m using Rails 2.3.11 and Ruby 1.8.7
Cheers!
Because Ruby is not a lazy language,
blog_with_page_path(:page_num => @posts_pages[:previous])gets evaluated as soon as you call it, regardless of whether the value ever gets used bylink_to_unless.