Module: Philiprehberger::Pluralize::Inflections

Defined in:
lib/philiprehberger/pluralize/inflections.rb

Overview

String inflection methods: camelCase, snake_case, titleize, humanize

Class Method Summary collapse

Class Method Details

.camel_case(str) ⇒ String

Convert an underscored or hyphenated string to PascalCase

Parameters:

  • str (String)

    the string to convert

Returns:

  • (String)

    PascalCase string



11
12
13
14
15
16
17
# File 'lib/philiprehberger/pluralize/inflections.rb', line 11

def self.camel_case(str)
  str.to_s
     .gsub(/[-_\s]+/, '_')
     .split('_')
     .map(&:capitalize)
     .join
end

.humanize(str) ⇒ String

Convert an underscored string to a human-readable form

Parameters:

  • str (String)

    the string to convert

Returns:

  • (String)

    humanized string



45
46
47
48
49
50
51
52
53
# File 'lib/philiprehberger/pluralize/inflections.rb', line 45

def self.humanize(str)
  result = str.to_s
              .gsub(/_id$/, '')
              .gsub('_', ' ')
              .strip
  return result if result.empty?

  result[0].upcase + result[1..]
end

.snake_case(str) ⇒ String

Convert a PascalCase or camelCase string to snake_case

Parameters:

  • str (String)

    the string to convert

Returns:

  • (String)

    snake_case string



23
24
25
26
27
28
29
# File 'lib/philiprehberger/pluralize/inflections.rb', line 23

def self.snake_case(str)
  str.to_s
     .gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2')
     .gsub(/([a-z\d])([A-Z])/, '\1_\2')
     .gsub(/[-\s]+/, '_')
     .downcase
end

.titleize(str) ⇒ String

Convert an underscored or hyphenated string to Title Case

Parameters:

  • str (String)

    the string to convert

Returns:

  • (String)

    titleized string



35
36
37
38
39
# File 'lib/philiprehberger/pluralize/inflections.rb', line 35

def self.titleize(str)
  snake_case(str)
    .gsub('_', ' ')
    .gsub(/\b\w/, &:upcase)
end