Tuesday, October 26, 2010

How to load i18N locale files in rails3 with our new gem

That is very simple. We'll create a gem with our own locale files, first, we create the locale files in our gem's lib/locales directory (en.yml and hu.yml for example). There would be our gem's .rb file in lib directory (example.rb). Don't forget to specify these files in gemspec. Now we can create a new method: translate_string in our 'lib/example.rb'.


class Example
require 'rubygems'
require 'active_support'
require 'i18n'


path=File.dirname(__FILE__)
I18n.load_path += Dir[ File.join(path, 'locales', '*.{rb,yml}') ]

def initialize
end

def translate_string(var)
  return I18n.t(var, :scope=>[:example, :vars])
end

end

Then, we can create our locale files 'lib/locales/en.yml' like this:


en:
  example:
    vars:
      title: example

And our lib/locales/hu.yml:


hu:
  example:
    vars:
      title: példa

Take care of spaces instead of tabs. After we build our gem and insert to Gemfile (what is in our Rails3 application) we can call our new class in our controller. Don't forget to restart your application before.



e=Example.new
e.translate_string("title")


This gives "example". That's all!

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.