Possible to check if exist in local data array

I am prototyping about 15+ pages which all look similar but need to include a partial with fields that are included based on a variable.

To make it more clear it is a search section for different user roles and the role and page defines if a certain filter should be shown on that page. There are many filters.

I want to create just one variable per page like:

page:

search: news

and then in the partial I want to check with each field if it should be shown:

 - if current_page.data.search == "news" OR "events" OR "whatever"
    // show this filter

Obviously this doesn’t work. I can only get it working if the condition is one string and an exact match of the variable.

Is there a way to make this work, so I don’t have to create a huge list of variables on the page?

I may have misunderstood but you could use a helper function like below. In the list hash, the keys represent the roles and the key’s value is an array of sections that the role has.

helpers do
  def role_has_section(role, search)
    list = {
      :admin => ['news', 'events', 'other'],
      :editor => ['news', 'events'],
      :subscriber => ['news']
    }

    if list.include?(role.to_sym)
      list[role.to_sym].include?(search)
    end
  end
end

And in your template use it like so.

- if role_has_section(current_page.data.role, current_page.data.search)
    // show filter

Sounds like you’re asking how to test for array membership:

filters = %w(news events whatever)
filters.include?(current_page.data.search)

or with Active Support:

current_page.data.search.in?(filters)
1 Like

Thank you very much for your help, I went for another solution, based on multiple partials. But it is good to know this solution, may I need it in the future.

For general data you can also use :

- if data.has_key? "google"
    TRUE

Putting this here cause I will likely google this again in the future :slightly_smiling: