Is there a Rails helper to show array content or its count if greater than X?

387 views Asked by At

I'm looking for a Ruby on Rails view helper which:

For example:

2.0.0p247 :001 > ["Audit", "Porsche", "Peugeot"].to_sentence("car", limit: 3)
 => "Audit, Porsche, and Peugeot"
2.0.0p247 :002 > ["Audit", "Porsche", "Peugeot", "Mitsubishi"].to_sentence("car", limit: 3)
 => "4 cars"

If this kind of helper doesn't exists I can create it but I would avoid to duplicate something existing.

3

There are 3 answers

0
Gareth On BEST ANSWER

Since the OP has asked for a one word answer, however useless that is, the answer is:

No.

1
La-comadreja On

you don't need a helper. You can just use a conditional in the view:

<% if array.length < min %>
  <% array.to_sentence(...) %>
<% elsif array.length > max %>
  <%= array.length %><%= string.pluralize %>
<% end %>
1
beck03076 On

This is a little shorter version

<% a = ["Audit", "Porsche", "Peugeot"] %>
<%= a.size < 4 ? a.to_sentence : a.size.to_s + " cars" %>