This week at my new job, I was once again reminded of the differences between coding alone and coding as part of a team.
One of my tickets required me to add a new column of data (indicating whether some products offered a free trial) to an existing table. If a free trial was available, a green checkmark was displayed; if not, a greyed-out checkmark was shown instead.
In our database, each product has a
free_trial? attribute 't' for "true", or 'f' for "false". Eager to demonstrate my Ruby skills, I dived into building and implementing a new method to accomplish my task. But then (thankfully!) I paused and asked myself: "Self, why not check to see how the green and grey checkmarks were generated for other table columns?" I found the following code block:
<% @aspects.each.with_index(1) do |aspect, index|%> <td class="aspect-<%= index %>"> <span class="icon-circle <%= green_or_grey(@product_aspects[product.id], aspect.feature) %>"> <i class="gg-check"></i> </span> </td> <% end %>
The key snippet is the
span statement which contains the
green_or_grey method. This method returns
aspect.feature is included in the
@product_aspects[product.id] array. However, in my case, I wasn't checking to see if an array contained an item; I was checking to see if an attribute was equal to 't' or 'f'.
I was stumped for some moments, before I realized that I could reference a one-element array containing the product's
free_trial? attribute, and then pass in 't' as my second argument. Then the
green_or_grey method would return
product.free_trial? == 't':
<%= green_or_grey([product.free_trial?], 't') %>
During code review, my teammates warmly commended me for figuring out a way to use the existing method (and of course I felt all warm and fuzzy inside lol). More importantly though, I felt proud of myself for taking the time to understand, respect and re-use the code I'd been given. In the moment, creating new code may feel easier and promise a certain level of progress, but could end up bloating and complicating your codebase unnecessarily.