ruby-on-railsactionviewhelper

rails actionview: How to "not show" attributes if receiving nil or something else


Is there an easy way to remove options attributes for the tag or content_tag helper?

<%= content_tag :div, content, {
  class: 'content',
  style: styles_hash.map{|x| "#{x[0].underscore.dasherize}: #{x[1]}"}.join('; '),
  data: {
    hyperlink: (hyperlink if hyperlink.present?)
  }
} %>

In this example, I'm wondering how to remove the data-hyperlink. Even if I throw a nil or false it stills displays as either data-hyperlink="null" or data-hyperlink="false" respectively. I need it to not display entirely if not present.


Solution

  • I've gotten a solution like this but I'd like to know if there is any better, or inside that data attribute?

    <%= content_tag :div, content, {
      class: 'content',
      style: styles_hash.map{|x| "#{x[0].underscore.dasherize}: #{x[1]}"}.join('; '),
      'data-hyperlink' => (hyperlink if hyperlink.present?)
    } %>