i18n_column
Introduction
This extension provides the capabilities of storing and retrieving translations from a single database column. The translations are stored as a JSON object i.e. “en”:“Home”,“de”:“Zuhause”.
The current and default locale are retrieved from the Rails Internationalization (I18n) API. Set the current locale on each request with i.e. I18n.locale = :de
. If not set the default locale will be taken: I18n.default_locale
. I18n.locale
is used as the JSON key to store a translation i.e. "en":"Home"
.
i18n_column
is tested with rails version 3.1.0
Installation
Gem
gem install i18n_column
Bundler
gem('i18n_column')
Example
Migration
class CreateNodes < ActiveRecord::Migration
def self.up
create_table(:nodes) do |t|
t.text(:name)
end
end
def self.down
drop_table(:nodes)
end
end
Model
class Node < ActiveRecord::Base
i18n_column(:name)
end
Controller
class ApplicationController < ActionController::Base
before_filter(:set_locale)
private
def set_locale
I18n.locale = params[:locale]
end
end
Set the default locale in config/application.rb file
config.i18n.default_locale = :de
Console
I18n.locale = :en
node = Node.create!(:name => 'Home') => {"en":"Home"}
node.name => 'Home'
I18n.locale = :de
node.name = 'Zuhause'
node.save! => {"en":"Home","de":"Zuhause"}
node.name => 'Zuhause'
Known issues
-
Rails versions greater than
3.0.1
: JSON hash instead of translation is displayed in form fields. Workaround:
f.text_field(:fname) instead of f.text_field(:name)
Copyright
Copyright © 2011 Philipp Ullmann. See LICENSE for details.