What is the best approach in order to localize images (buttons and other content) in a i18n rails app?
In a recent app I tried i18n translations for the first time with some success, although the code may be a bit messy.
In the application_controller I have:
class ApplicationController < ActionController::Base
before_filter :set_locale
AVAILABLE_LOCALES = I18n.backend.available_locales
private
##########
# Internationalisation
# For more information see http://guides.rubyonrails.org/i18n.html
# Additional locale starting points can be found here http://github.com/svenfuchs/rails-i18n/tree/a0be8dd219ccce6716955566ee557cc75122cb33/rails/locale
def tld
domain_array = request.subdomains.split(".")
domain_array[0] == "www" ? domain_array[1].to_s : domain_array[0].to_s
end
def available_locales
AVAILABLE_LOCALES
end
def set_locale
I18n.locale = extract_locale_from_subdomain
end
def extract_locale_from_subdomain
(available_locales.include? tld.to_sym) ? tld : nil unless tld.blank?
end
end
This basically looks up the appropriate language from the subdomain specified, so http://en.mysite.com is in English and http://it.mysite.com is in Italian.
Next is your views, where you simply use:
<%= t(:click_to_edit) %>
Lastly, in config/locales create a en.yml file with the translations required:
en:
admin_menu: "Admin Menu"
Arabic: "Arabic"
back: "Back"
Basque: "Basque"
blogs: "Blogs"
blog_list: "Blog List"
blogroll: "Blogroll"
The Italian file contains:
it:
admin_menu: "Menu Amministrazione"
Arabic: "Italian Arabic"
back: "Indietro"
Basque: "Italian Basque"
I usually inject the locale name in every path or in the image name. In the first case, create different folders for different locales
/public/images/en/file.png
/public/images/it/file.png
image_tag("#{I18n.locale}/file.png")
In the second case
/public/images/file.it.png
/public/images/file.en.png
image_tag("file.#{I18n.locale}.png")
I usually prefer the second solution because there are many assets I don't need to localize and I often need to keep translated/common assets in the same folders to take advantage of convenction-over-configuration pattern.