Module: Normatron::Filters::CamelizeFilter

Extended by:
Helpers
Defined in:
lib/normatron/filters/camelize_filter.rb

Class Method Summary collapse

Methods included from Helpers

acronym_regex, acronyms, evaluate_regexp, inflections, mb_send

Class Method Details

.evaluate(input, first_letter_case = :upper) ⇒ String

TODO:

Performance tests

TODO:

Exception class

Converts strings to UpperCamelCase by default and to lowerCamelCase if the :lower argument is given. camelize will also convert ‘/’ to ‘::’ which is useful for converting paths to namespaces. As a rule of thumb you can think of camelize as the inverse of underscore, though there are cases where that does not hold:

"SSLError".underscore.camelize # => "SslError"

This filter has a similar behavior to ActiveSupport::Inflector#camelize, but with following differences:

  • Uses UTF-8 charset

  • Affects accented characters

Examples:

CamelizeFilter.evaluate("active_record/errors")         #=> "ActiveRecord::Errors"
CamelizeFilter.evaluate("active_record/errors", :upper) #=> "ActiveRecord::Errors"
CamelizeFilter.evaluate("active_record/errors", :lower) #=> "activeRecord::Errors"

Using as ActiveRecord::Base normalizer

normalize :attribute_a, :with => :camelize
normalize :attribute_b, :with => [:custom_filter, :camelize]
normalize :attribute_c, :with => [[:camelize, :lower]]
normalize :attribute_d, :with => [{:camelize => :lower}]
normalize :attribute_e, :with => [:custom_filter, [:camelize, :lower]]
normalize :attribute_f, :with => [:custom_filter, {:camelize => :lower}]

Parameters:

  • input (String)

    A character sequence

  • first_letter_case (Symbol) (defaults to: :upper)

    :lower for lowerCamelCase or :upper for UpperCamelCase

Returns:

  • (String)

    The camelized character sequence or the object itself

See Also:



38
39
40
41
42
43
44
45
46
47
# File 'lib/normatron/filters/camelize_filter.rb', line 38

def self.evaluate(input, first_letter_case = :upper)
  return input unless input.kind_of?(String)

  if first_letter_case == :upper
    string = input.sub(/^[\p{L}\d]*/u) { acronyms[$&] || mb_send(:capitalize, $&) }
  else first_letter_case == :lower
    string = input.sub(/^(?:#{acronym_regex}(?=\b|[\p{L}_])|\p{Word}*_)/u) { mb_send(:downcase, $&) }
  end
  string.gsub!(/(?:_|(\/))([\p{L}\d]*)/iu) { "#{$1}#{acronyms[$2] || mb_send(:capitalize, $2)}" }.gsub!('/', '::')
end