Skip to content
Skye Shaw edited this page Jun 12, 2015 · 5 revisions

Gettext is different than the typical I18n usage as it does not require the creation of aliases (keys) for your translations.

Rails

See gettext_i18n_rails

Standalone

Translation Files

Only PO files are required. I18n has its own PO file parser. The filename(s) must be named after the locale, e.g., en.po, pt.po, etc...

Here's a very basic PO file, pt.po:

# Some optional headers
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=INTEGER; plural=EXPRESSION;\n"

msgid "bye"
msgstr "tchau"

msgid "bunny rabbit adventure"
msgstr "a aventura da coelhinha" 

msgid "time for bed!"
msgstr "nana nenê!"

For more info on the format see the PO File section of the gettext manual. Also checkout Wikipedia's gettext page.

I18n Code

require "i18n"

include I18n::Gettext::Helpers

I18n::Backend::Simple.include(I18n::Backend::Gettext)
I18n.load_path << Dir["*.po"]  # Load all PO file in current directory
I18n.locale = :pt 

puts _("bye") # tchau
puts _("bunny rabbit adventure") # a aventura da coelhinha

# Or 
puts _("bye", :locale => "pt") # tchau

For more info see I18n::Gettext::Helpers's docs.

Using I18n.t with gettext is not recommended. Doing so will cause problems if your translation string contains a period ".":

require "i18n"

include I18n::Gettext::Helpers

# Pretend we loaded a PO file
I18n.backend.store_translations(:pt, "See you soon." => "Até breve.")
I18n.locale = :pt

puts I18n.t "See you soon." # translation missing: pt.See you soon
puts _("See you soon.")     # Até breve.