Question

Is there a better way to write this code? It appears a little verbose to me.

I'm using sunspot SOLR, the stored() method returns either nil or an array of values, I always want the first value if it exists, or just print an empty string is fine.

 <td><%= search_result.stored(:seo_title).first() if search_result.stored(:seo_title).present?  %></td>
  <td><%= search_result.stored(:title).first() if search_result.stored(:title).present? %></td>
  <td><%= search_result.stored(:publish_at).first() if search.result.stored(:publish_at).present? %></td>
Was it helpful?

Solution

<%- [:seo_title, :title, :publish_at].each do |key| %>
  <td><%= search_result.stored(key).try(:first) %></td>
<% end %>

Anyway, if there are just 3 keys, I'd rather stay with explicitly rendering all 3 table cells, the loop here has the same number of lines and does not look much better. So an alternative is:

<td><%= search_result.stored(:seo_title).try(:first) %></td>
<td><%= search_result.stored(:title).try(:first) %></td>
<td><%= search_result.stored(:publish_at).try(:first) %></td>

OTHER TIPS

Another option is to write like this:

<td><%= (search_result.stored(:seo_title) || []).first %></td>
<td><%= (search_result.stored(:title) || []).first %></td>
<td><%= (search_result.stored(:publish_at) || []).first %></td>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top