module Inflector

Public Instance Methods

camelize(lower_case_and_underscored_word, first_letter_in_uppercase = true) click to toggle source
# File lib/ext/string.rb, line 4
def camelize(lower_case_and_underscored_word, first_letter_in_uppercase = true)
  if first_letter_in_uppercase
    lower_case_and_underscored_word.to_s.gsub(/\/(.?)/) { "::#{$1.upcase}" }.gsub(/(?:^|_)(.)/) { $1.upcase }
  else
    lower_case_and_underscored_word.to_s[0].chr.downcase + camelize(lower_case_and_underscored_word)[1..-1]
  end
end
constantize(camel_cased_word) click to toggle source
# File lib/ext/string.rb, line 35
def constantize(camel_cased_word)
  names = camel_cased_word.split('::')
  names.shift if names.empty? || names.first.empty?

  constant = Object
  names.each do |name|
    constant = constant.const_defined?(name) ? constant.const_get(name) : constant.const_missing(name)
  end
  constant
end
dasherize(underscored_word) click to toggle source
# File lib/ext/string.rb, line 22
def dasherize(underscored_word)
  underscored_word.gsub(/_/, '-')
end
demodulize(class_name_in_module) click to toggle source
# File lib/ext/string.rb, line 26
def demodulize(class_name_in_module)
  class_name_in_module.to_s.gsub(/^.*::/, '')
end
foreign_key(class_name, separate_class_name_and_id_with_underscore = true) click to toggle source
# File lib/ext/string.rb, line 30
def foreign_key(class_name, separate_class_name_and_id_with_underscore = true)
  underscore(demodulize(class_name)) + (separate_class_name_and_id_with_underscore ? "_id" : "id")
end
ordinalize(number) click to toggle source
# File lib/ext/string.rb, line 58
def ordinalize(number)
  if (11..13).include?(number.to_i % 100)
    "#{number}th"
  else
    case number.to_i % 10
      when 1; "#{number}st"
      when 2; "#{number}nd"
      when 3; "#{number}rd"
      else    "#{number}th"
    end
  end
end
underscore(camel_cased_word) click to toggle source
# File lib/ext/string.rb, line 12
def underscore(camel_cased_word)
  word = camel_cased_word.to_s.dup
  word.gsub!(/::/, '/')
  word.gsub!(/([A-Z]+)([A-Z][a-z])/,'\1_\2')
  word.gsub!(/([a-z\d])([A-Z])/,'\1_\2')
  word.tr!("-", "_")
  word.downcase!
  word
end