Module: Extlib::Inflection

Defined in:
lib/aqua/support/string_extensions.rb

Overview

English Nouns Number Inflection.

This module provides english singular <-> plural noun inflections.

Class Method Summary collapse

Class Method Details

.camelize(lower_case_and_underscored_word, *args) ⇒ Object

By default, camelize converts strings to UpperCamelCase.

camelize will also convert ‘/’ to ‘::’ which is useful for converting paths to namespaces

Examples:

"active_record".camelize #=> "ActiveRecord"
"active_record/errors".camelize #=> "ActiveRecord::Errors"


54
55
56
# File 'lib/aqua/support/string_extensions.rb', line 54

def camelize(lower_case_and_underscored_word, *args)
  lower_case_and_underscored_word.to_s.gsub(/\/(.?)/) { "::" + $1.upcase }.gsub(/(^|_)(.)/) { $2.upcase }
end

.classify(name) ⇒ Object

Take an underscored name and make it into a camelized name

Examples:

"egg_and_hams".classify #=> "EggAndHam"
"post".classify #=> "Post"


42
43
44
# File 'lib/aqua/support/string_extensions.rb', line 42

def classify(name)
  camelize(singularize(name.to_s.sub(/.*\./, '')))
end

.constantize(camel_cased_word) ⇒ Object

Constantize tries to find a declared constant with the name specified in the string. It raises a NameError when the name is not in CamelCase or is not initialized.

Examples:

"Module".constantize #=> Module
"Class".constantize #=> Class


92
93
94
95
96
97
98
# File 'lib/aqua/support/string_extensions.rb', line 92

def constantize(camel_cased_word)
  unless /\A(?:::)?([A-Z]\w*(?:::[A-Z]\w*)*)\z/ =~ camel_cased_word
    raise NameError, "#{camel_cased_word.inspect} is not a valid constant name!"
  end
 
  Object.module_eval("::#{$1}", __FILE__, __LINE__)
end

.humanize(lower_case_and_underscored_word) ⇒ Object

Capitalizes the first word and turns underscores into spaces and strips _id. Like titleize, this is meant for creating pretty output.

Examples:

"employee_salary" #=> "Employee salary"
"author_id" #=> "Author"


81
82
83
# File 'lib/aqua/support/string_extensions.rb', line 81

def humanize(lower_case_and_underscored_word)
  lower_case_and_underscored_word.to_s.gsub(/_id$/, "").gsub(/_/, " ").capitalize
end

.underscore(camel_cased_word) ⇒ Object

The reverse of camelize. Makes an underscored form from the expression in the string.

Changes ‘::’ to ‘/’ to convert namespaces to paths.

Examples:

"ActiveRecord".underscore #=> "active_record"
"ActiveRecord::Errors".underscore #=> active_record/errors


67
68
69
70
71
72
73
# File 'lib/aqua/support/string_extensions.rb', line 67

def underscore(camel_cased_word)
  camel_cased_word.to_s.gsub(/::/, '/').
  gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').
  gsub(/([a-z\d])([A-Z])/,'\1_\2').
  tr("-", "_").
  downcase
end