Your code will be cleaner if you pass the classes in as an array. <%= content_tag :div, content, class: [‘a’, ‘b’, nil, ‘c’] %>; the nil elements will be ignored. Doing that, you can create the array elsewhere in your code however you want and then pass it in.
Here is what I use. It is also based on classNames from JavaScriptland. I might remove the .join() now that I know you can pass a string array to class. Thanks Andrew.
def class_names(*classes)
class_array = [(classes.shift if classes.first.is_a? String), classes.first.select { |_, v| v }.keys]
class_array.compact.join(" ")
end
<% content_tag(:div, class: class_names('btn', 'btn-danger': false, 'btn-success': true, btn_other: true)) %>
I find this a powerful helper for building the class attribute. I even wrote up a small post on the kinds of use-cases and edge-cases it solves for: Fractaled Mind