Filtering data from yaml file

I’m using a similar code to the one in “Data Files” to parse data from a yaml file, so my code looks like this:

<% data.items.each do |item| %>
  <h2><%= item.name %></h2>
  <p><%= item.description %></p>
<% end %>

What I would like to do now, is for users to filter the items rendered, depending on if they contain certain value or not. For example, there would be a “Free” link, and it should hide the items that are not free.

The values from the yaml file look like this:

name: "Balsamiq"
description: "A rapid low-fidelity UI wireframing tool."
price: "free"

So items like this, should be shown and the rest hidden upon user’s action (then, filters would be multiple so user can choose several criteria at the same time.)

I’m a bit lost on how to continue from here, if this could be done directly on my template, or if I should relay on JavaScript.

I’ve been looking around on StackOverflow for a while now with not significant progress, so any pointers would be appreciated.

You can do something like this to get only the items with price: free

<% data.items.select { |item| item.price == 'free' }.each do |item| %>

If you want to show or hide stuff based on user input, you might just want to give the items a class or data attribute so you can do the filtering with js:

<% data.items.each do |item| %>
  <div class="item #{'free' if item.price == 'free'}">
    ...
  </div>

<% end %>

Thanks Tom, I’m struggling with different approaches even parsing a JSON instead, with JavaScript.

If I use your solution, and I have several criteria (such as “free”), how bad / good practice is to add 6-7 classes to each item just to later on identify them to show / hide them?

I don’t think adding classes to provide functionality is a problem. As long as the experience for the user is pleasant and fast.

You could also add all the relevant criteria to a data attribute like data-filters="[free,expensive,cheap]" by using join https://apidock.com/ruby/Array/join. There’s probably a ton of other ways, just go for whatever works for you and your users!

Thanks Tom! In the end, as I wanted to accomplish some more complex interactions, I ended up parsing a JSON with JS. I’m keeping the classes approach for filtering. Thanks! You have been very helpful : )

1 Like