Method: Fusu::String::Methods#camelize

Defined in:
lib/fusu/string/methods.rb

#camelize(term, uppercase_first_letter = true) ⇒ Object

Converts strings to UpperCamelCase. If the uppercase_first_letter parameter is set to false, then produces lowerCamelCase.

Also converts ‘/’ to ‘::’ which is useful for converting paths to namespaces.

camelize('active_model')                # => "ActiveModel"
camelize('active_model', false)         # => "activeModel"
camelize('active_model/errors')         # => "ActiveModel::Errors"
camelize('active_model/errors', false)  # => "activeModel::Errors"

As a rule of thumb you can think of camelize as the inverse of #underscore, though there are cases where that does not hold:

camelize(underscore('SSLError'))        # => "SslError"


33
34
35
36
37
38
39
40
41
42
43
# File 'lib/fusu/string/methods.rb', line 33

def camelize(term, uppercase_first_letter = true)
  string = term.to_s
  if uppercase_first_letter
    string = string.sub(/^[a-z\d]*/) { |match| match.capitalize }
  else
    string = string.sub(/^(?:#{ACRONYM_REGEX}(?=\b|[A-Z_])|\w)/) { |match| match.downcase }
  end
  string.gsub!(/(?:_|(\/))([a-z\d]*)/i) { "#{$1}#{$2.capitalize}" }
  string.gsub!("/".freeze, "::".freeze)
  string
end