Skip to content

Instantly share code, notes, and snippets.

@yoavmatchulsky
Created January 21, 2014 11:50
Show Gist options
  • Save yoavmatchulsky/8538659 to your computer and use it in GitHub Desktop.
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'
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