Module: Normatron::Filters::CamelizeFilter

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

Overview

Converts strings to UpperCamelCase by default and to lowerCamelCase if the :lower argument is given.

It 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 it affects UTF-8 characters too.

Examples:

Out of box

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

Using as model 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}]

See Also:

Class Method Summary collapse

Methods included from Helpers

acronym_regex, acronyms, evaluate_regexp, inflections, mb_send

Class Method Details

.call(input, camel = :upper) ⇒ String

Performs input conversion according to filter requirements.

This method returns the object itself when the first argument is not a String.

Parameters:

  • input (String)

    The String to be filtered

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

    :lower for lowerCamelCase or :upper for UpperCamelCase

Returns:

  • (String)

    A new camelized String



46
47
48
49
50
51
52
53
# File 'lib/normatron/filters/camelize_filter.rb', line 46

def self.call(input, camel = :upper)
  return input unless input.kind_of?(String)

  string = mb_send(:downcase, input)
  string.sub!(/^[^_|\/]+/) { camel == :upper ? acronyms[$&] || mb_send(:capitalize, $&) : $& }
  string.gsub!(/(?:(\/)|_)([^\/|_]+)/) { "#{$1}#{acronyms[$2] || mb_send(:capitalize, $2)}" }
  string.gsub("/", "::")
end