Module: RailsViewHelpers::CommonHelper

Defined in:
app/helpers/rails_view_helpers/common_helper.rb

Overview

Utililty methods used by Bootstrap::*Helper classes

Constant Summary collapse

ArgumentError =
Class.new(::ArgumentError)

Instance Method Summary collapse

Instance Method Details

#arrayify_and_stringify_elements(arg) ⇒ Array of String

Returns a new Array of String from arg.

Examples:

arrayify_and_stringify_elements(nil)            #=> [] 
arrayify_and_stringify_elements('foo')          #=> ["foo"]
arrayify_and_stringify_elements('foo bar')      #=> ["foo", "bar"]
arrayify_and_stringify_elements([:foo, 'bar'])  #=> ["foo", "bar"]

Parameters:

  • arg (String, Array)

Returns:

  • (Array of String)


31
32
33
34
35
36
37
38
39
# File 'app/helpers/rails_view_helpers/common_helper.rb', line 31

def arrayify_and_stringify_elements(arg)
  return false if arg == false
  
  case
  when arg.blank? then []
  when arg.is_a?(Array) then arg
  else arg.to_s.strip.split(/\s/)
  end.map(&:to_s)
end

#canonicalize_options(hash) ⇒ Hash

Returns a new Hash with:

  • keys converted to Symbols

  • the :class key has its value converted to an Array of String

Examples:

canonicalize_options("id" => "ID", "class" => "CLASS")  # => {:id=>"ID", :class=>["CLASS"]} 
canonicalize_options(:class => 'one two')               # => {:class=>["one", "two"]}
canonicalize_options("class" => [:one, 2])              # => {:class=>["one", "2"]} 

Parameters:

  • hash (Hash)

    typically an options param to a method call

Returns:

  • (Hash)

Raises:



15
16
17
18
19
20
21
# File 'app/helpers/rails_view_helpers/common_helper.rb', line 15

def canonicalize_options(hash)
  raise ArgumentError.new("expected a Hash, got #{hash.inspect}") unless hash.is_a?(Hash)

  hash.symbolize_keys.tap do |h|
    h[:class] = arrayify_and_stringify_elements(h[:class])
  end
end

#ensure_class(hash, klasses) ⇒ Hash

Returns new (canonicalized) Hash where :class value includes klasses.

Examples:

ensure_class({class: []}, 'foo')                               #=> {class: 'foo'}
ensure_class({class: ['bar'], id: 'my-id'}, ['foo', 'foo2'])   #=> {:class=>["bar", "foo", "foo2"], :id=>"my-id"}

Parameters:

  • hash (Hash)
  • klasses (String, Array)

    one or more classes to add to the :class key of hash

Returns:

  • (Hash)


49
50
51
52
53
54
55
56
57
# File 'app/helpers/rails_view_helpers/common_helper.rb', line 49

def ensure_class(hash, klasses)
  hash = canonicalize_options(hash)
  
  hash.dup.tap do |h|
    Array(klasses).map(&:to_s).each do |k|
      h[:class] << k unless h[:class].include?(k)
    end
  end
end