Вопрос

I am implementing a view count feature for particular web pages in Ruby on Rails. I use haml lists to achieve my end. (The JavaScript library takes the list and render it as dropdowns.)

Here is the code snippet:

%li.action
  = link_to t(question.views_count.to_s + ' views')

My problem here is that the V in views is capitalized in the output and view is pluralized even for 0 and 1 number of views. Is there any way I can deal with these issues?

Это было полезно?

Решение

You're doing it wrong, you should be letting the I18N system (i.e. the t method) deal with the pluralization on its own. Proper plural handling is horribly complicated, don't try to do it yourself with string manipulation. You're using the t method but it can do a lot more for you.

From the I18N Guide:

The :count interpolation variable has a special role in that it both is interpolated to the translation and used to pick a pluralization from the translations according to the pluralization rules defined by CLDR:

I18n.backend.store_translations :en, :inbox => {
  :one => '1 message',
  :other => '%{count} messages'
}

I18n.translate :inbox, :count => 2
# => '2 messages'

So assuming you have your message database properly set up, then you would do something like this:

t(:views, :count => question.views_count)

And your English translation file would have something like this:

views:
  one: "1 view"
  other: "%{count} views"

Другие советы

see this link for pluralize http://apidock.com/rails/ActionView/Helpers/TextHelper/pluralize

try in your console, for example

1.9.3p125 :028 > pluralize(2, 'View')
 => "2 Views"

Update

try in your console and use capitalize

"view".capitalize 
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top