class HornOfPlenty::CoreExt::String

Constants

SINGULARIZATION_RULES

rubocop:disable Metrics/LineLength

Public Class Methods

camelize(other, uppercase_first_letter = true) click to toggle source

rubocop:enable Metrics/LineLength

# 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) click to toggle source
# 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) click to toggle source
# 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) click to toggle source
# 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