Module: Inflector

Extended by:
Inflector
Included in:
Inflector
Defined in:
lib/active_support/inflector.rb

Overview

The Inflector transforms words from singular to plural, class names to table names, modularized class names to ones without, and class names to foreign keys.

Instance Method Summary collapse

Instance Method Details

#camelize(lower_case_and_underscored_word) ⇒ Object


28
29
30
# File 'lib/active_support/inflector.rb', line 28

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

#classify(table_name) ⇒ Object


48
49
50
# File 'lib/active_support/inflector.rb', line 48

def classify(table_name)
  camelize(singularize(table_name))
end

#constantize(camel_cased_word) ⇒ Object


57
58
59
60
61
# File 'lib/active_support/inflector.rb', line 57

def constantize(camel_cased_word)
  camel_cased_word.split("::").inject(Object) do |final_type, part| 
    final_type = final_type.const_get(part)
  end
end

#demodulize(class_name_in_module) ⇒ Object


40
41
42
# File 'lib/active_support/inflector.rb', line 40

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) ⇒ Object


52
53
54
55
# File 'lib/active_support/inflector.rb', line 52

def foreign_key(class_name, separate_class_name_and_id_with_underscore = true)
  Inflector.underscore(Inflector.demodulize(class_name)) + 
    (separate_class_name_and_id_with_underscore ? "_id" : "id")
end

#humanize(lower_case_and_underscored_word) ⇒ Object


36
37
38
# File 'lib/active_support/inflector.rb', line 36

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

#pluralize(word) ⇒ Object


6
7
8
9
10
11
12
13
14
15
# File 'lib/active_support/inflector.rb', line 6

def pluralize(word)
  result = word.to_s.dup

  if uncountable_words.include?(result.downcase)
    result
  else
    plural_rules.each { |(rule, replacement)| break if result.gsub!(rule, replacement) }
    result
  end
end

#singularize(word) ⇒ Object


17
18
19
20
21
22
23
24
25
26
# File 'lib/active_support/inflector.rb', line 17

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

  if uncountable_words.include?(result.downcase)
    result
  else
    singular_rules.each { |(rule, replacement)| break if result.gsub!(rule, replacement) }
    result
  end
end

#tableize(class_name) ⇒ Object


44
45
46
# File 'lib/active_support/inflector.rb', line 44

def tableize(class_name)
  pluralize(underscore(class_name))
end

#underscore(camel_cased_word) ⇒ Object


32
33
34
# File 'lib/active_support/inflector.rb', line 32

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