Thoughts, information and reflections about technology

Shading Cells in Ruby depending on the contents of the cell


I wanted to change the background color of a cell depending on if the contents of and expires field was past or not.  This could be useful for dashboard type apps or pages. i.e. red/yellow/green

index.html.erb

<% @user_messages.each do |user_message| %>
 <tr>
<td><%= user_message.message.html_safe %></td>
<% get_expires(user_message.expires) %>  

 
<td style=”background-color: <%=$expires_color%>”> <%= $expires_formatted.strftime(“%m/%d/%y”) %> <br> <%= $expires_formatted.strftime(“%I:%M %p”) %></td>
<td><%= link_to ‘Show’, user_message %></td>
<td><%= link_to ‘Edit’, edit_user_message_path(user_message) %></td>
<td><%= link_to ‘Destroy’, user_message, method: :delete, data: { confirm: ‘Are you sure?’ } %></td>
</tr>
<%
end %>
   <td><%= user_message.message.html_safe %></td>   <% get_expires(user_message.expires) %>        <td style=”background-color: <%=$expires_color%>”> <%= $expires_formatted.strftime(“%m/%d/%y”) %> <br> <%= $expires_formatted.strftime(“%I:%M %p”) %></td>   <td><%= link_to ‘Show’, user_message %></td>   <td><%= link_to ‘Edit’, edit_user_message_path(user_message) %></td>   <td><%= link_to ‘Destroy’, user_message, method: :delete, data: { confirm: ‘Are you sure?’ } %></td> </tr><% end %>

The def in the controller is

helper_method :get_expires
def get_expires(expires)
# this grabs the expires date, then sets a variable for the strftime function in user_messagesindex    # If the expires date/time is past, a variable is set which is used in the TD style statement for that cell    $expires_color = ‘lightgreen’
$expires_formatted = expires
if $expires_formatted.past?
$expires_color = ‘#ffcccc’
end
end

The key to making this work is to pass the date you want to the def with

<% get_expires(user_message.expires) %> 

Then the def sets the appropriate value for the shading. which is used in the style statement for the TD

 <td style=”background-color<%=$expires_color%>”>

 

If the background color is too much, you can simply change the style to change the text color instead.

Similar Posts:

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact me
Archives
Categories