An “else” condition for link_to_unless_current
Every time I get frustrated with an aspect of Rails, it turns out that it’s just my idiocy and not actually something to do with Rails.
Most recently, I wanted to code this algorithm:
If on the current page show <a href="blah1">link 1</a> else show <a href="blah2>link 2</a>
Rails has, of course, the nifty link_to_unless_current, but all that does is show the text of the link:
If on the current page show link else show <a href="blah">link</a>
That’s not quite what I’m looking for. But when I was looking up link_to_unless_current in the docs, I realized that there IS an else condition on link_to_unless_current. The function takes a block as its last parameter, and that’s what gives you the “else.”
This code, in a view:
<%= link_to_unless_current('Link text', my_url) { 'Alternate text' } %>
produces this algorithmic result:
If on the current page show Alternate text else show <a href="my_url">Link text</a>
Mission accomplished.
Ranunculus occidentalis var. occidentalis (Ranunculaceae); Western buttercup
