From 4f75840d72b96fff34d65b59480da7d6c7494120 Mon Sep 17 00:00:00 2001 From: Pratik Naik Date: Wed, 2 Jul 2008 13:25:17 +0100 Subject: Add Inflection rules for String#humanize. [#535 state:resolved] [dcmanges] Signed-off-by: Pratik Naik --- activesupport/lib/active_support/inflector.rb | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) (limited to 'activesupport/lib') diff --git a/activesupport/lib/active_support/inflector.rb b/activesupport/lib/active_support/inflector.rb index 8d55ad27ac..6651569d33 100644 --- a/activesupport/lib/active_support/inflector.rb +++ b/activesupport/lib/active_support/inflector.rb @@ -30,10 +30,10 @@ module ActiveSupport class Inflections include Singleton - attr_reader :plurals, :singulars, :uncountables + attr_reader :plurals, :singulars, :uncountables, :humans def initialize - @plurals, @singulars, @uncountables = [], [], [] + @plurals, @singulars, @uncountables, @humans = [], [], [], [] end # Specifies a new pluralization rule and its replacement. The rule can either be a string or a regular expression. @@ -76,9 +76,20 @@ module ActiveSupport (@uncountables << words).flatten! end + # Specifies a humanized form of a string by a regular expression rule or by a string mapping. + # When using a regular expression based replacement, the normal humanize formatting is called after the replacement. + # When a string is used, the human form should be specified as desired (example: 'The name', not 'the_name') + # + # Examples: + # human /_cnt$/i, '\1_count' + # human "legacy_col_person_name", "Name" + def human(rule, replacement) + @humans.insert(0, [rule, replacement]) + end + # Clears the loaded inflections within a given scope (default is :all). # Give the scope as a symbol of the inflection type, the options are: :plurals, - # :singulars, :uncountables. + # :singulars, :uncountables, :humans. # # Examples: # clear :all @@ -209,7 +220,10 @@ module ActiveSupport # "employee_salary" # => "Employee salary" # "author_id" # => "Author" def humanize(lower_case_and_underscored_word) - lower_case_and_underscored_word.to_s.gsub(/_id$/, "").gsub(/_/, " ").capitalize + result = lower_case_and_underscored_word.to_s.dup + + inflections.humans.each { |(rule, replacement)| break if result.gsub!(rule, replacement) } + result.gsub(/_id$/, "").gsub(/_/, " ").capitalize end # Removes the module part from the expression in the string. -- cgit v1.2.3