Class: HornOfPlenty::CoreExt::String

Inherits:
Object
  • Object
show all
Defined in:
lib/horn_of_plenty/core_ext/string.rb

Constant Summary collapse

SINGULARIZATION_RULES =

rubocop:disable Metrics/LineLength

[
  [/(database)s$/i, '\1'],
  [/(quiz)zes$/i, '\1'],
  [/(matr)ices$/i, '\1ix'],
  [/(vert|ind)ices$/i, '\1ex'],
  [/^(ox)en/i, '\1'],
  [/(alias|status)(es)?$/i, '\1'],
  [/(octop|vir)(us|i)$/i, '\1us'],
  [/^(a)x[ie]s$/i, '\1xis'],
  [/(cris|test)(is|es)$/i, '\1is'],
  [/(shoe)s$/i, '\1'],
  [/(o)es$/i, '\1'],
  [/(bus)(es)?$/i, '\1'],
  [/^(m|l)ice$/i, '\1ouse'],
  [/(x|ch|ss|sh)es$/i, '\1'],
  [/(m)ovies$/i, '\1ovie'],
  [/(s)eries$/i, '\1eries'],
  [/([^aeiouy]|qu)ies$/i, '\1y'],
  [/([lr])ves$/i, '\1f'],
  [/(tive)s$/i, '\1'],
  [/(hive)s$/i, '\1'],
  [/([^f])ves$/i, '\1fe'],
  [/(^analy)(sis|ses)$/i, '\1sis'],
  [/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)(sis|ses)$/i, '\1sis'],
  [/([ti])a$/i, '\1um'],
  [/(n)ews$/i, '\1ews'],
  [/(ss)$/i, '\1'],
  [/s$/i, ''],
].freeze

Class Method Summary collapse

Class Method Details

.camelize(other, uppercase_first_letter = true) ⇒ Object

rubocop:enable Metrics/LineLength



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/horn_of_plenty/core_ext/string.rb', line 37

def self.camelize(other, uppercase_first_letter = true)
  string = if uppercase_first_letter
             other.sub(/^[a-z\d]*/) do
               $&.capitalize
             end
           else
             other.sub(/^(?:(?=\b|[A-Z_])|\w)/) do
               $&.downcase
             end
           end

  string.gsub!(%r{(?:_|(/))([a-z\d]*)}i) do
    "#{Regexp.last_match(1)}#{Regexp.last_match(2).capitalize}"
  end

  string.gsub!(%r{/}, '::')

  string
end

.constantize(other) ⇒ Object



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/horn_of_plenty/core_ext/string.rb', line 57

def self.constantize(other)
  names = other.split('::')
  names.shift if names.empty? || names.first.empty?

  constant = Object

  names.each do |name|
    constant = if constant.const_defined?(name)
                 constant.const_get(name)
               else
                 constant.const_missing(name)
               end
  end

  constant
end

.singularize(word) ⇒ Object



84
85
86
87
88
89
90
91
92
# File 'lib/horn_of_plenty/core_ext/string.rb', line 84

def self.singularize(word)
  result = word.to_s.dup

  SINGULARIZATION_RULES.each do |(rule, replacement)|
    break if result.sub!(rule, replacement)
  end

  result
end

.underscore(other) ⇒ Object



74
75
76
77
78
79
80
81
82
# File 'lib/horn_of_plenty/core_ext/string.rb', line 74

def self.underscore(other)
  word = other.to_s.dup
  word.gsub!(/::/, '/')
  word.gsub!(/([A-Z\d]+)([A-Z][a-z])/, '\1_\2')
  word.gsub!(/([a-z\d])([A-Z])/, '\1_\2')
  word.tr!('-', '_')
  word.downcase!
  word
end