Module: ClassName::Helper

Included in:
ClassName
Defined in:
lib/class_name/helper.rb

Instance Method Summary collapse

Instance Method Details

#class_name(*css_map) ⇒ String

Conditionally joins a set of CSS class names into a single string

read more about this [module](www.carlosramireziii.com/a-cleaner-way-to-set-multiple-conditional-css-classes-for-link-to.html)

Examples:

Create a css string from a complex object

class_name(
  "base",
  "carl-the-fog",
  hidden: article.has_chart?,
  [:foo, :bar] => false,
  [:foobar] => true
)
=> "base carl-the-fog foobar"

Parameters:

  • css_map (Hash)

    a mapping of CSS class names to boolean values

Returns:

  • (String)

    a combined string of CSS classes where the value was true



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/class_name/helper.rb', line 20

def class_name(*css_map)
  classes = []
  css_map.flatten.reject(&:blank?).each do |css, bool|
    case css.class.to_s
    when "Integer", "Fixnum"
      classes << ClassName::NumberConverter.to_word(css)
    when "String"
      classes << css
    when "Array"
      classes << css.join(" ")
    when "Hash"
      css.each do |hash_css, bool|
        classes << hash_css if bool
      end
    end
  end

  classes.join(" ")
end