Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to avoid this if else logic in partial? -- Rails 3.1

I have a partial which is used all over the site. I have an image in the partial that I want to link to a certain page on all pages except one particular controller action.

1. Is there way to put in the following href without 2 if else sets?...

<a href="#">
  <img src="#" />
</a>

I'm trying to avoid doing this:

<% if (current controller != xyz) %>
  <a href="#">
<% end %>
   <img src="#" />
<% if (current controller != xyz) %>
  </a>
<% end %>

2. How can I actually check which controller called this partial?

The above code is only pseudo code.

PS. I know this isn't that much repetition, but I'm just using this simplified case as an example. Curious if there's something in Rails I don't know about to avoid this.

like image 570
Jacob Avatar asked Jan 29 '26 06:01

Jacob


2 Answers

This is exactly what link_to_if is for!

link_to_if(controller_name == 'xyz', image_tag('src'), 'http://target.com')

This will add the image whether the condition is true or not, and wrap it in the link only when the condition is true. There's also the related link_to_unless which may be more semantically appropriate in your case.

Edit: I've updated the example above to use the correct code for checking the controller name. There's a method available in the view, controller_name that returns a lowercase version of the name of your controller. It's also in the params hash.

like image 68
Emily Avatar answered Jan 30 '26 20:01

Emily


It boils down to this question: "What do you want to duplicate".

In your question, you duplicate the if test. In a counter example (below) I will duplicate the img tag.

Counter Example

<% if (current controller != xyz) %>
  <a href="#">
    <img src="#"/>
  </a>
<% end %>
<% if (current controller == xyz) %>
    <img src="#"/>
<% end %>

My preference is to duplicate the thing that is least likely to change and, when I don't know which is least likely to change, then default to the shortest amount of duplication.

Shortest is vague on purpose. The image tag, as written, appears to be the shortest, but I suspect the if part will usually be the shortest.

like image 34
DwB Avatar answered Jan 30 '26 18:01

DwB