aboutsummaryrefslogtreecommitdiffstats
path: root/activesupport
diff options
context:
space:
mode:
authorJosé Valim <jose.valim@gmail.com>2011-11-06 02:20:06 -0800
committerJosé Valim <jose.valim@gmail.com>2011-11-06 02:20:06 -0800
commita02bb72cf73a3d6852cade9ecb7c7c1743d0ad10 (patch)
tree07ca8ce7d688fa894fd7fe4253a43ea60c3b7291 /activesupport
parent62512b9fb9750b0dda4acb65e4fc368260e3b66c (diff)
parent52fa34faee76ca54b1b394ea3a25dfee42491c22 (diff)
downloadrails-a02bb72cf73a3d6852cade9ecb7c7c1743d0ad10.tar.gz
rails-a02bb72cf73a3d6852cade9ecb7c7c1743d0ad10.tar.bz2
rails-a02bb72cf73a3d6852cade9ecb7c7c1743d0ad10.zip
Merge pull request #3537 from dvyjones/refactor-pluralize-singularize
Refactored pluralize and singularize into a common method
Diffstat (limited to 'activesupport')
-rw-r--r--activesupport/lib/active_support/inflector/methods.rb34
1 files changed, 18 insertions, 16 deletions
diff --git a/activesupport/lib/active_support/inflector/methods.rb b/activesupport/lib/active_support/inflector/methods.rb
index e76ee60dd7..9eba02b6f0 100644
--- a/activesupport/lib/active_support/inflector/methods.rb
+++ b/activesupport/lib/active_support/inflector/methods.rb
@@ -21,14 +21,7 @@ module ActiveSupport
# "words".pluralize # => "words"
# "CamelOctopus".pluralize # => "CamelOctopi"
def pluralize(word)
- result = word.to_s.dup
-
- if word.empty? || inflections.uncountables.include?(result.downcase)
- result
- else
- inflections.plurals.each { |(rule, replacement)| break if result.gsub!(rule, replacement) }
- result
- end
+ apply_inflections(word, inflections.plurals)
end
# The reverse of +pluralize+, returns the singular form of a word in a string.
@@ -40,14 +33,7 @@ module ActiveSupport
# "word".singularize # => "word"
# "CamelOctopi".singularize # => "CamelOctopus"
def singularize(word)
- result = word.to_s.dup
-
- if inflections.uncountables.any? { |inflection| result =~ /\b(#{inflection})\Z/i }
- result
- else
- inflections.singulars.each { |(rule, replacement)| break if result.gsub!(rule, replacement) }
- result
- end
+ apply_inflections(word, inflections.singulars)
end
# By default, +camelize+ converts strings to UpperCamelCase. If the argument to +camelize+
@@ -311,5 +297,21 @@ module ActiveSupport
part.empty? ? acc : "#{part}(::#{acc})?"
end
end
+
+ # Applies inflection rules for +singluralize+ and +pluralize+.
+ #
+ # Examples:
+ # apply_inflections("post", inflections.plurals) # => "posts"
+ # apply_inflections("posts", inflections.singulars) # => "post"
+ def apply_inflections(word, rules)
+ result = word.to_s.dup
+
+ if word.empty? || inflections.uncountables.any? { |inflection| result =~ /\b#{inflection}\Z/i }
+ result
+ else
+ rules.each { |(rule, replacement)| break if result.gsub!(rule, replacement) }
+ result
+ end
+ end
end
end