From 4cb4ae9ac0276d6f2aba7db633a90062aba2be6c Mon Sep 17 00:00:00 2001 From: Rizwan Reza Date: Sat, 15 May 2010 13:13:25 +0430 Subject: [PATCH] Adds the ability to manipulate pluralize by passing a block with passing tests. --- actionpack/lib/action_view/helpers/text_helper.rb | 17 ++++++++++++++--- actionpack/test/template/text_helper_test.rb | 1 + 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/actionpack/lib/action_view/helpers/text_helper.rb b/actionpack/lib/action_view/helpers/text_helper.rb index 0e1bc13..522c5f9 100644 --- a/actionpack/lib/action_view/helpers/text_helper.rb +++ b/actionpack/lib/action_view/helpers/text_helper.rb @@ -173,7 +173,8 @@ module ActionView # Attempts to pluralize the +singular+ word unless +count+ is 1. If # +plural+ is supplied, it will use that when count is > 1, otherwise - # it will use the Inflector to determine the plural form + # it will use the Inflector to determine the plural form. If a block + # is given, the count and word are yielded. # # ==== Examples # pluralize(1, 'person') @@ -187,8 +188,18 @@ module ActionView # # pluralize(0, 'person') # # => 0 people - def pluralize(count, singular, plural = nil) - "#{count || 0} " + ((count == 1 || count =~ /^1(\.0+)?$/) ? singular : (plural || singular.pluralize)) + # + # pluralize(2, 'person') do |count, word| + # "*#{count}* #{word}" + # end + # # => *2* people + def pluralize(count, singular, plural = nil, &block) + word = (count == 1 || count == '1' || count =~ /^1(\.0+)?$/) ? singular : (plural || singular.pluralize) + if block_given? + concat(capture((count || 0), word, &block)) + else + "#{count || 0} #{word}" + end end # Wraps the +text+ into lines no longer than +line_width+ width. This method diff --git a/actionpack/test/template/text_helper_test.rb b/actionpack/test/template/text_helper_test.rb index 8b6c107..d081c96 100644 --- a/actionpack/test/template/text_helper_test.rb +++ b/actionpack/test/template/text_helper_test.rb @@ -249,6 +249,7 @@ class TextHelperTest < ActionView::TestCase assert_equal("10 buffaloes", pluralize(10, "buffalo")) assert_equal("1 berry", pluralize(1, "berry")) assert_equal("12 berries", pluralize(12, "berry")) + assert_equal("13 glasses", pluralize(12, "glasses") { |count, word| "#{count + 1} #{word}"}) end def test_auto_link_parsing -- 1.6.5.2