I love it when a very small bit of code makes my life easier and my code simpler. Today I’ve defined a new helper method for one of my application and its done just that. This is the code
def action_name_is?(*actions) actions.include?(controller.action_name) end
So why is that so useful?
I am a great believer in DRY (Don’t Repeat Yourself) coding which Ruby and Rails make very easy. One way to achieve this is to use partials quite a lot, which I do. I often find that there are substantial section of code that can be split out into a partial and then used in a number of views.
Quite often in the middle of this partial code, there are some elements that are view specific. Rather than leave those elements out of the partial or letting them be defined in the controller via instance variables, I sometimes prefer to have modifiers in the partials that alter the code depending on the action name.
A common example is a series of navigation links. The containing block and most of the links will probably need to be the same across views, but some links may be action specific.
In the past I’ve used code like this:
<% if controller.action_name == 'list' %> <p><%= link_to('Reports', :controller => 'reports', :view => 'list' -%></p> <% end %>
This can be neatened by using content_tag to:
<%= content_tag("p", link_to('Reports', :controller => 'reports', :view => 'list' ) if controller.action_name == 'list' %>
But even then things can get a little complicated if you want an action to do something in a small number of views. action_name_is? makes this simpler.
<%= content_tag("p", link_to('Reports', :controller => 'reports', :view => 'list' ) if action_name_is?('list') %>
Now if you want the link to appear in both the list and show views, its simply a case of passing ‘show’ to the method as well as ‘list’:
<%= content_tag("p", link_to('Reports', :controller => 'reports', :view => 'list' ) if action_name_is?('list', 'show') %>
And of course there is nothing to stop you using it negatively. That is, to use it with ‘unless’ to define which views the link shouldn’t appear in:
<%= content_tag("p", link_to('Reports', :controller => 'reports', :view => 'list' ) unless action_name_is?('list', 'show') %>