mirror of
https://github.com/rails/rails.git
synced 2022-11-09 12:12:34 -05:00
Merge pull request #3537 from dvyjones/refactor-pluralize-singularize
Refactored pluralize and singularize into a common method
This commit is contained in:
commit
a02bb72cf7
1 changed files with 18 additions and 16 deletions
|
@ -21,14 +21,7 @@ module ActiveSupport
|
||||||
# "words".pluralize # => "words"
|
# "words".pluralize # => "words"
|
||||||
# "CamelOctopus".pluralize # => "CamelOctopi"
|
# "CamelOctopus".pluralize # => "CamelOctopi"
|
||||||
def pluralize(word)
|
def pluralize(word)
|
||||||
result = word.to_s.dup
|
apply_inflections(word, inflections.plurals)
|
||||||
|
|
||||||
if word.empty? || inflections.uncountables.include?(result.downcase)
|
|
||||||
result
|
|
||||||
else
|
|
||||||
inflections.plurals.each { |(rule, replacement)| break if result.gsub!(rule, replacement) }
|
|
||||||
result
|
|
||||||
end
|
|
||||||
end
|
end
|
||||||
|
|
||||||
# The reverse of +pluralize+, returns the singular form of a word in a string.
|
# The reverse of +pluralize+, returns the singular form of a word in a string.
|
||||||
|
@ -40,14 +33,7 @@ module ActiveSupport
|
||||||
# "word".singularize # => "word"
|
# "word".singularize # => "word"
|
||||||
# "CamelOctopi".singularize # => "CamelOctopus"
|
# "CamelOctopi".singularize # => "CamelOctopus"
|
||||||
def singularize(word)
|
def singularize(word)
|
||||||
result = word.to_s.dup
|
apply_inflections(word, inflections.singulars)
|
||||||
|
|
||||||
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
|
|
||||||
end
|
end
|
||||||
|
|
||||||
# By default, +camelize+ converts strings to UpperCamelCase. If the argument to +camelize+
|
# By default, +camelize+ converts strings to UpperCamelCase. If the argument to +camelize+
|
||||||
|
@ -311,5 +297,21 @@ module ActiveSupport
|
||||||
part.empty? ? acc : "#{part}(::#{acc})?"
|
part.empty? ? acc : "#{part}(::#{acc})?"
|
||||||
end
|
end
|
||||||
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
|
||||||
end
|
end
|
||||||
|
|
Loading…
Reference in a new issue