Cleaner way to do this in Rails
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 Ra开发者_开发知识库ils?
<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
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.
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
精彩评论