#256 I18n Backends
Mar 07, 2011 | 11 minutes | Views
Internationalization is easy to add in Rails, but the YAML files can be difficult to manage. In this episode I show how to use Redis for managing the translations through a web interface.
- Download:
- source codeProject Files in Zip (99.2 KB)
- mp4Full Size H.264 Video (19.2 MB)
- m4vSmaller H.264 Video (12.4 MB)
- webmFull Size VP8 Video (28.2 MB)
- ogvFull Size Theora Video (26.1 MB)
Resources
- Episode 138: I18n
- i18n
- i18n-active_record
- Redis
- Crafting Rails Applications
- Full episode source code
bash
rails g controller translations index
brew install redis
rails g controller translations index brew install redis
Gemfile
gem 'redis'
gem 'redis'
config/initializers/i18n_backend.rb
TRANSLATION_STORE = Redis.new
I18n.backend = I18n::Backend::Chain.new(I18n::Backend::KeyValue.new(TRANSLATION_STORE), I18n.backend)
TRANSLATION_STORE = Redis.new I18n.backend = I18n::Backend::Chain.new(I18n::Backend::KeyValue.new(TRANSLATION_STORE), I18n.backend)
translations_controller.rb
def index
@translations = TRANSLATION_STORE
end
def create
I18n.backend.store_translations(params[:locale], {params[:key] => params[:value]}, :escape => false)
redirect_to translations_url, :notice => "Added translation"
end
def index @translations = TRANSLATION_STORE end def create I18n.backend.store_translations(params[:locale], {params[:key] => params[:value]}, :escape => false) redirect_to translations_url, :notice => "Added translation" end
home/index.html.erb
<h1><%= t "welcome" %></h1>
<h1><%= t "welcome" %></h1>
translations/index.html.erb
<h1>Translations</h1>
<ul>
<% @translations.keys.each do |key| %>
<li><%= key %>: <%= @translations[key] %></li>
<% end %>
</ul>
<h2>Add Translation</h2>
<%= form_tag translations_path do %>
<p>
<%= label_tag :locale %><br />
<%= text_field_tag :locale %>
</p>
<p>
<%= label_tag :key %><br />
<%= text_field_tag :key %>
</p>
<p>
<%= label_tag :value %><br />
<%= text_field_tag :value %>
</p>
<p><%= submit_tag "Submit" %></p>
<% end %>
<h1>Translations</h1> <ul> <% @translations.keys.each do |key| %> <li><%= key %>: <%= @translations[key] %></li> <% end %> </ul> <h2>Add Translation</h2> <%= form_tag translations_path do %> <p> <%= label_tag :locale %><br /> <%= text_field_tag :locale %> </p> <p> <%= label_tag :key %><br /> <%= text_field_tag :key %> </p> <p> <%= label_tag :value %><br /> <%= text_field_tag :value %> </p> <p><%= submit_tag "Submit" %></p> <% end %>
config/locales/en.yml
en:
welcome: "Welcome"
en: welcome: "Welcome"

