Jeremy Thomas
Jeremy Thomas

Reputation: 6684

Using single-line looping to generate HTML classes in a Rails view

I have an hash in the format:

@meals = [
        {
            name: 'Roasted Chicken A La Ratatouille',
            description: '',
            tags: ['chicken'],
            type: ['program'],
            image_url: ''
        },
        {
            name: 'Turkey Nuggets with Buffalo Cauliflower & Spinach',
            description: '',
            tags: ['turkey'],
            type: ['program', 'veggies'],
            image_url: ''
        }
     ]

and I'd like to be able to unpack the meal type as class names for the element:

<% meals.shuffle.each do |meal| %>

  <!-- Line in question --> 
  <div class="item col-3 p-2 a b <%= meal[:type].each {|t| t } %>">
  <!-- End line in question --> 

    <div class="card">
      <img class="card-img-top" src="<%= meal[:image_url] %>">
      <div class="card-body">
        <h5 class="card-title font-medium"><%= meal[:name] %></h5>
      </div>
      <div class="card-footer text-muted justify-content-center row">
        <% meal[:tags].each do |tag| %>
          <span style="margin: 2px;" class="badge bg-info-gradiant pointer"><%= tag %></span>
        <% end -%>
      </div>
    </div>
  </div>
<% end %>

But when the view renders, it displays as:

<div class="item col-3 p-2 a b ["program"]" style="position: absolute; left: 295px; top: 0px;">
    <div class="card" style="height: 399px;">
        ...
    </div>
</div>

Where program is displayed within the brackets. Is there a different way to accomplish this so that the values within the array are applied as class names?

Upvotes: 1

Views: 38

Answers (1)

Rory O&#39;Kane
Rory O&#39;Kane

Reputation: 30398

You can use Array#join to explicitly convert the array of classes into a string of space-separated class names:

<div class="item col-3 p-2 a b <%= meal[:type].join(' ') %>">

How it works:

> meal[:type]
=> ["program", "veggies"]
> meal[:type].join(' ')
=> "program veggies"

Note that meal[:type].each does not do what you think it does. It calls the block for each element in the meal[:type] array with the expectation that the block performs a side effect (e.g. logging something or saving something), and then it returns the unmodified meal[:type] array. If you wanted to get a new array, you would have to use Array#map instead:

> meal[:type].each { |t| t.reverse }
=> ["program", "veggies"] # the block doesn’t affect the return value
> meal[:type].map { |t| t.reverse }
=> ["margorp", "seiggev"] # the block affects each returned element

Upvotes: 2

Related Questions