Created
January 21, 2014 11:50
-
-
Save yoavmatchulsky/8538659 to your computer and use it in GitHub Desktop.
Add #pluralize_with_parenthesis to ActiveSupport::Inflector and Rails helpers. Example:
'article'.pluralize_with_parenthesis => 'article(s)'
'person'.pluralize_with_parenthesis => 'people'
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module ActiveSupport | |
module Inflector | |
def pluralize_with_parenthesis(word) | |
rule, replacement = find_inflections(word, inflections.plurals) | |
if replacement =~ /\A\w+\Z/ | |
word.gsub!(rule, "(#{replacement})") | |
else | |
pluralize(word) | |
end | |
end | |
private | |
# find the inflection rules for +pluralize_with_parenthesis+. | |
def find_inflections(word, rules) | |
result = word.to_s.dup | |
if word.empty? || inflections.uncountables.any? { |inflection| result =~ /\b#{inflection}\Z/i } | |
false | |
else | |
replacements = rules.collect { |(rule, replacement)| [rule, replacement] if result.gsub!(rule, replacement) }.compact | |
replacements.first | |
end | |
end | |
end | |
end | |
class String | |
def pluralize_with_parenthesis | |
ActiveSupport::Inflector.pluralize_with_parenthesis(self) | |
end | |
end | |
module ActionView | |
module Helpers | |
module TextHelper | |
def pluralize_with_parenthesis(word) | |
word.pluralize_with_parenthesis | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment