Module: Corefines::String::Camelcase

Defined in:
lib/corefines/string.rb

Instance Method Summary collapse

Instance Method Details

#camelcase(*separators) ⇒ String #camelcase(first_letter, *separators) ⇒ String

Returns a copy of the str converted to camelcase. When no :upper or :lower is specified, then it leaves the first character of a word (after camelization) unchanged.

Examples:

"camel case".camelcase          # => "camelCase"
"Camel case".camelcase          # => "CamelCase"
"camel_case__4you!".camelcase   # => "camelCase4you!"
"camel_case__4_you!".camelcase  # => "camelCase4You!"

Overloads:

  • #camelcase(*separators) ⇒ String

    Examples:

    "camel-case yay!".camelcase('-')          # => "camelCase yay!"
    "camel::ca-se-y".camelcase(':', '-')      # => "camelCaSeY"
    "camel42case".camelcase(/[0-9]+/)         # => "camelCase"

    Parameters:

    • *separators (String, Regexp)

      the patterns used to determine where capitalization should occur. Defaults to /_+/ and \s+.

  • #camelcase(first_letter, *separators) ⇒ String

    Examples:

    "camel case".camelcase(:upper)            # => "CamelCase"
    "camel-case yay!".camelcase(:upper, '-')  # => "CamelCase Yay!"

    Parameters:

    • first_letter (:upper, :lower)

      desired case of the first character of a word - :upper to be upcased, or :lower to be downcased.

    • *separators (String, Regexp)

      the patterns used to determine where capitalization should occur. Defaults to /_+/ and \s+.

Returns:

  • (String)

    a copy of the str converted to camelcase.


46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/corefines/string.rb', line 46

module Camelcase
  refine ::String do
    def camelcase(*separators)
      first_letter = separators.shift if ::Symbol === separators.first
      separators = [/_+/, /\s+/] if separators.empty?

      self.dup.tap do |str|
        separators.compact.each do |s|
          s = "(?:#{::Regexp.escape(s)})+" unless s.is_a? ::Regexp
          str.gsub!(/#{s}([a-z\d])/i) { $1.upcase }
        end

        case first_letter
        when :upper
          str.gsub!(/(\A|\s)([a-z])/) { $1 + $2.upcase }
        when :lower
          str.gsub!(/(\A|\s)([A-Z])/) { $1 + $2.downcase }
        end
      end
    end
  end
end