1

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
unor
  • 92,415
  • 26
  • 211
  • 360
devmind
  • 13
  • 2
  • This question is specifically about Nanoc, but any Ruby solution would be appreciated. This is _NOT_ a Rails issue. But yes, I've read the Rails i18n documentation, sadly it does not apply in my case. – devmind Jun 17 '14 at 13:41

1 Answers1

1

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.

  • 1
    It does exactly want I wanted to do, thanks. I just added `I18n.enforce_available_locales = false` after requiring the i18n Gem to silence the warning when compiling since I'm not going to use any other locale than French. – devmind Jun 18 '14 at 09:09