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


22
23
24
# File 'lib/active_support/inflector.rb', line 22

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


42
43
44
# File 'lib/active_support/inflector.rb', line 42

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

#constantize(camel_cased_word) ⇒ Object


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

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


34
35
36
# File 'lib/active_support/inflector.rb', line 34

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


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

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


30
31
32
# File 'lib/active_support/inflector.rb', line 30

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
# File 'lib/active_support/inflector.rb', line 6

def pluralize(word)
  result = word.to_s.dup
  plural_rules.each do |(rule, replacement)|
    break if result.gsub!(rule, replacement)
  end
  return result
end

#singularize(word) ⇒ Object


14
15
16
17
18
19
20
# File 'lib/active_support/inflector.rb', line 14

def singularize(word)
  result = word.to_s.dup
  singular_rules.each do |(rule, replacement)|
    break if result.gsub!(rule, replacement)
  end
  return result
end

#tableize(class_name) ⇒ Object


38
39
40
# File 'lib/active_support/inflector.rb', line 38

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

#underscore(camel_cased_word) ⇒ Object


26
27
28
# File 'lib/active_support/inflector.rb', line 26

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