rubydatelocalizationinternationalizationnanoc

Date localization with nanoc's "created_at"


I found lot of articles talking about i18n with Rails, Nanoc, but nothing about a really simple (I think) thing: how to internationalize a date on a nanoc article.

I have a really simple setup, for example here is a snippet of my index.html page:

<%= link_to(post[:title], post.path) %> - <%= post[:created_at] %>

This is a dummy article:

---
title: Test
created_at: 1 January 1970
---

Wich gives this result when compiled:

Test - 1 January 1970 

But I would like the date to be in French, like this:

Test - 1 Janvier 1970

Solution

  • You can use Rails' internationalization gem, i18n, on its own for this task. Here's a simple example:

    1. If you're using Bundler, edit your nanoc project's Gemfile to include the i18n gem:

      gem 'i18n'
      

      Otherwise, install the gem locally on your computer (for which you'll probably need superuser privileges):

      gem install i18n
      
    2. Add a French translation file at, say, tr/fr.yml, to your nanoc project. Place in it these (minimal) contents:

      ---
      fr:
        date:
          formats:
            default: ! '%-d %B %Y'
          month_names:
          - 
          - janvier
          - février
          - mars
          - avril
          - mai
          - juin
          - juillet
          - août
          - septembre
          - octobre
          - novembre
          - décembre
      
    3. Add a helper for performing the translation, for instance at lib/translate_date.rb, with this code:

       require 'date'
       require 'i18n'
      
       # Load our translation files
       I18n.load_path = Dir['./tr/*.yml']
      
       # Set the default locale to French
       I18n.locale = :fr
      
       # Translates a date string into the default locale.
       def translate_date(date)
         I18n.l Date.parse(date, '%d %B %Y')
       end
      
    4. Now place this in your index.html file,

      <%= link_to(post[:title], post.path) %> - <%= translate_date(post[:created_at]) %>
      

      and you should get the output you want.