3

I have a big problem with pluralize : when 0, it does pluralize the word

pluralize(@posts.size,"post")

if @posts.size equals 0 :

0 posts

if @posts.size equals 1 :

1 post

if @posts.size equals 2 or more :

n posts

As it should not add an s when 0 by default, I'm lost. Is there anyone seeing what's wrong right here ?

Ben
  • 5,030
  • 6
  • 53
  • 94

2 Answers2

3

Any number not 1 is considered plural. Instead of saying:

You have 0 posts.

the correct English sentence would be:

You do not have any posts.

Take a look at here and here.

Edit: Your request is fairly large and may not be possible for anyone (atleast for me) to succinctly put it in a single post. I would rather suggest you read through Internationalization (popularly called i18n) doc.

http://guides.rubyonrails.org/i18n.html

Basically, there are 2 things, Translations and Inflectors.

Inflectors are rules defining how a string or a pattern substitutes into singular or plural or if it's uncountable. Example, plural for is is are is defined as an inflector.

I18n helps you define locale specified humanized text for a string. If you see in your Rails project, inside config folder, you will see a folder called locales, which contains single YAML file for each locale. Such humanized text for locales are called translations.

pluralize is a function that is defined at 3 places:

  1. Inside Inflector module.
  2. As a String's instance method.
  3. As a Helper method inside ActionView.

Usually in Rails, we call the helper method, which may make a call to String's method which in turns calls the Inflector's method.

You try adding following code inside config/initializers/filename.rb and trying running again:

module ActionView
  module Helpers
    module TextHelper
      def pluralize(count, singular, plural = nil)
        "#{count || 0} " + ([0, 1, '0', '1'].include?(count) ? singular : (plural || singular.pluralize))
      end
    end
  end
end

This will return 0 post but for the default locale only which is en. If you wish to do it for a specific locale, call the String pluralize function with selected locale and pass it to above function as 3 argument. Example, for fr locale, you may try something like:

pluralize 0, "post", "post".pluralize(:fr) # => will return for fr locale

Ask more questions here at SO and let experts explain in more detail.

Hope this helps you.

Community
  • 1
  • 1
Harsh Gupta
  • 4,348
  • 2
  • 25
  • 30
0

I use another method for this :

In my view:

= t('counts.offers', count: project.nb_offers)
# t() is a shortcut for I18n.translate

The first parameter is the path in your file locale file, the second is the thing you want to count.

Then, in your config/locales/xx.yml (fr in my case):

fr:
  counts:
    offers:
      zero: 0 offre
      one: 1 offre
      other: "%{count} offres"

So I don't have to create a new config file, simply use locales

cercxtrova
  • 1,555
  • 13
  • 30