Request log analyzer

Since we have been using I18n in Partigi for the last months we have notice that we were always repeating ourselves when localising a sentence like this:

This film has been saved by 4 friends

What is special in this sentece is that, depending on the number of friends that saved the film, the sentence could be "This film has been saved by one friend". It can be solved with pluralize helper, but it requires the counter to be at the beginning of the sentence.

Finally we decided to adopt a small convention: if a translation has a parameter count then, if count is singular the key for the translation will be the one in the view, but if it's plural, it will be the one in the view plus a suffix _plural. For example:

Before we had:

   <% if @reviews_count == 1 %>
     <%= t('films.saved_by_friends', :count => @reviews_count) %>
   <% else %>
     <%= t('films.saved_by_friends_plural', :count => @reviews_count) %>
   <% end %>
 

And now, with this hack:

   <%= t('films.saved_by_friends', :count => @reviews_count) %>
 

The hack is this (put it where you like more):

 module I18n 
   class << self
     # Returns true if a given key exists
     def exists?(key, options = {}) 
       locale = options.delete(:locale) || I18n.locale
       backend.exists?(locale, key, options = {})
     end
     
     # Overwrite I18n.trasnlate method
     def translate(key, options = {})
       locale = options.delete(:locale) || I18n.locale
       if options[:count] && options[:count].to_i != 1
         plural_key = "#{key}_plural" 
         if exists?(plural_key)
           key = plural_key
         end
       end
       backend.translate(locale, key, options)
     rescue I18n::ArgumentError => e
       raise e if options[:raise]
       send(@@exception_handler, e, locale, key, options)
     end
   end
 end
 
 

The good thing is that if the pluralized key doesn't exists, your views won't be broken, so you can start using it now and change your views when you have time.