views:

47

answers:

2

Hi,

I have some code in one of my views like this. I feel that it has too many if else conditions. All it does is checking for the ActiveRecord Object's status and setting the image. Is there a better way to do the following in Rails?

<td class="notification_msg">
  <% if notification.status == NOTIFICATION_STATUS.index("Failure") %>
     <img src="images/failure.png" style="vertical-align: middle"/>
  <% elsif notification.status == NOTIFICATION_STATUS.index("Success") %>
     <img src="images/success.png" style="vertical-align: middle"/>
  <% elsif notification.status == NOTIFICATION_STATUS.index("Warning") %>
     <img src="images/warning.gif" style="vertical-align: middle"/>
  <% else %>
     <img src="images/unknown.gif" style="vertical-align: middle"/>
  <% end %>
  <%= notification.message %> <%= cta_links_for(notification) -%>
</td>

Thanks

+3  A: 

You can change

 <img src="images/success.png" style="vertical-align: middle"/>

In

= image_tag "success.png

Then use CSS:

.notification_msg img{vertical-align:middle;}

I'm confused by why you display success.png on failure, I'll add more info to my answer once you explained that :)


From what I understand here what I would have done:

erb:

<td class="notification_msg">
  <%= image_tag "#{notification.status}.png" %>
  <%= notification.message %> <%= cta_links_for(notification) -%>
</td>

css:

.notification_msg img{vertical-align:middle;}

It's not error-proof but I hope it'll give you an idea

marcgg
Thanks for your instant response. If we put `#{notifiction.status}.png` directly, wouldnt that increase the coupling between the image files and the view ?
Bragboy
I am planning to use ur style as it looks tidy .. thanks..
Bragboy
@bragboy: yes, but it's not neceserally a bad thing (imho)
marcgg
+5  A: 

I'd pull the logic into a helper. Your erb:

<td class="notification_msg"> 
  <%= notification_image(notification.status) %> 
  <%= notification.message %> <%= cta_links_for(notification) -%> 
</td>

Then in your view helper:

def notification_image(status)
  name = NOTIFICATION_STATUS[status].downcase
  return image_tag "#{name}.png"
end

And of course, no inline styles. So put .notification_msg img{vertical-align:middle;} in your css file.

Mark Thomas