Module: CommandKit::Inflector

Defined in:
lib/command_kit/inflector.rb

Overview

Note:

If you need something more powerful, checkout dry-inflector

A very simple inflector.

API:

  • semipublic

Class Method Summary collapse

Class Method Details

.camelize(name) ⇒ String

Converts an under_scored name to a CamelCased name.

Parameters:

  • The under_scored name.

Returns:

  • The CamelCased name.

Raises:

  • The given under_scored string contained non-alpha-numeric characters.

API:

  • semipublic



96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
# File 'lib/command_kit/inflector.rb', line 96

def self.camelize(name)
  scanner    = StringScanner.new(name.to_s)
  new_string = String.new

  until scanner.eos?
    if (word = scanner.scan(/[A-Za-z\d]+/))
      word.capitalize!
      new_string << word
    elsif (numbers = scanner.scan(/[_-]\d+/))
      new_string << "_#{numbers[1..]}"
    elsif scanner.scan(/[_-]+/)
      # skip
    elsif scanner.scan(%r{/})
      new_string << '::'
    else
      raise(ArgumentError,"cannot convert string to CamelCase: #{scanner.string.inspect}")
    end
  end

  new_string
end

.dasherize(name) ⇒ String

Replaces all underscores with dashes.

Parameters:

  • The under_scored name.

Returns:

  • The dasherized name.

API:

  • semipublic



80
81
82
# File 'lib/command_kit/inflector.rb', line 80

def self.dasherize(name)
  name.to_s.tr('_','-')
end

.demodularize(name) ⇒ String

Removes the namespace from a constant name.

Parameters:

  • The constant name.

Returns:

  • The class or module's name, without the namespace.

API:

  • semipublic



25
26
27
# File 'lib/command_kit/inflector.rb', line 25

def self.demodularize(name)
  name.to_s.split('::').last
end

.underscore(name) ⇒ String

Converts a CamelCased name to an under_scored name.

Parameters:

  • The CamelCased name.

Returns:

  • The resulting under_scored name.

Raises:

  • The given string contained non-alpha-numeric characters.

API:

  • semipublic



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/command_kit/inflector.rb', line 41

def self.underscore(name)
  scanner    = StringScanner.new(name.to_s)
  new_string = String.new

  until scanner.eos?
    if (separator = scanner.scan(/[_-]+/))
      new_string << ('_' * separator.length)
    else
      if (capitalized = scanner.scan(/[A-Z][a-z\d]+/))
        new_string << capitalized
      elsif (uppercase = scanner.scan(/[A-Z][A-Z\d]*(?=[A-Z_-]|$)/))
        new_string << uppercase
      elsif (lowercase = scanner.scan(/[a-z][a-z\d]*/))
        new_string << lowercase
      else
        raise(ArgumentError,"cannot convert string to underscored: #{scanner.string.inspect}")
      end

      if (separator = scanner.scan(/[_-]+/))
        new_string << ('_' * separator.length)
      elsif !scanner.eos?
        new_string << '_'
      end
    end
  end

  new_string.downcase!
  new_string
end