I am new to ruby & rails and have started building an application.
My goal is to build this in a way I can easily translate the contents of the rails app and display the website contents in a locale preferred by registered user.
Appreciate any inputs on some of the best practices or references to any documentation to read, to build a web application that can be easily translated?
Thanks,
Krish.
Check out the Rails Internationalization (I18n) API. It does everything you've described.
Also check out Globalize3, it became a standard for model translations. Very useful.
You can use ready_for_i18n plugin that convert your erb to desired form.It saves some time.
You'd definetely watch this talk: http://www.youtube.com/watch?v=CTu4iHWGDyE
Here are some tips or best practices I noted while working through Internationalization of a Rails app. (It's possible that some of them are now outdated).
Before I get into a list here's some clarification between localization and translation that was helpful to me:
Definitions:
App localization and model translations are separate concerns. Figure out which one of those (or both) it is, that you need.
The way I use them here:
App localization: Localization your app to a locale.
Model translation: Translation your model/data into a language.
Example: Give me the french translation (model translation) of the resource in my Spanish site (app localization)
I use Globalize for model translations.
Helpful Tips/ Best Practices:
Some of the following are clearly just helpful tips while working in the Context of Rails + Globalize, some of them might be more than that... possibly best practices.
I18n.locale refers to and sets the locale of the app. When using Globalize, Globalize.locale refers to and sets the locale for model/data translations.
Set both I18n.locale and Globalize.locale on every request. Since these variables are set in Thread, it will avoid some hard-to-replicate bugs.
Set Globalize.locale to I18n.locale right after setting I18n.locale. This allows for model translations to default to the locale of the app. (On my Spanish site, I expect data to be in Spanish, by default).
Change Globalize.locale (and notI18n.locale) to change model translation.
Reset I18n.locale and Globalize.locale after every test. In rspec
RSpec.configure do |config|
config.after(:each) do
I18n.locale = :en
Globalize.locale = :en
end
end
Either use subdomain, or subfolder in the url to refer to the locale of the app.
Use a language parameter to specify the language of the data.
When you work on your rails app, you will probably use default_url_options to use I18n.locale as the default locale parameter for your route / path helpers. However this doesn't work in tests. I picked up a solution from this github issue on rspec-rails.
I monkey patch ActionDispatch::Routing::RouteSet like so:
class ActionDispatch::Routing::RouteSet
def url_for_with_locale_fix(options={})
url_for_without_locale_fix(options.merge(:locale => I18n.locale))
end
alias_method_chain :url_for, :locale_fix
end
Set up a translate helper t as a wrapper around the I18n.t method
module I18nHelper
def t string, options = {}
I18n.t string, options
end
end
RSpec.configure do |config|
config.include I18nHelper
end
This is mini-pattern I use. You can check it out: http://developers-note.blogspot.com/2012/01/rails-i18n-good-practice.html
Related
What I would like to do is utilize the I18n localization structure to handle organziation-specific naming schemas, independently of the users actual local. Something like:
Default Naming Schema
show.en.yml
en:
show:
title: Component
Organization A Nameing Schema
show.org_a.yml
org_a:
show:
title: Widget
Organization B Nameing Schema
show.org_b.yml
org_b:
show:
title: Sprocket
I've tried to just set a custom local using I18n.locale = organziation.slug.to_sym || I18n.default_locale (where slug would be org_a, org_b, etc.), but that just yields a :org_a is not a valid locale error. Unfortunately, searching for possible solutions has not been all that fruitful.
Is there a way to add custom locals, or should I be approaching this problem a different way (using Rails 6)?
This works in Rails 4.2 (since that is what I have easy access to right now) to allow for custom locales but it should work for Rails 6 as well (or something similar to this):
I18n.available_locales = I18n.available_locales + [:org_a, :org_b]
I18n.locale = organziation.slug.to_sym || I18n.default_locale
Maybe append to the available locales early on in a config file, or similar.
After coding the app in English, I updated the language file (pt-BR.yml), the 'config/application.rb' (setting the default to pt-BR), and the 'inflections.rb'in order to have the error messages in my local language.
However, Rails now does not find my model because its logic does not pluralize in English anymore.
Is there a way to prevent Rails to use the local default language in models and controllers?
Or is there a better coding practice for it?
Thanks.
You can configure your inflections.rb rather than converting the default lang. You can do that like so:
ActiveSupport::Inflector.inflections(:es) do |inflect|
inflect.plural(/$/, 's')
inflect.plural(/([^aeéiou])$/i, '\1es')
inflect.plural(/([aeiou]s)$/i, '\1')
inflect.plural(/z$/i, 'ces')
inflect.plural(/á([sn])$/i, 'a\1es')
inflect.plural(/é([sn])$/i, 'e\1es')
inflect.plural(/í([sn])$/i, 'i\1es')
inflect.plural(/ó([sn])$/i, 'o\1es')
inflect.plural(/ú([sn])$/i, 'u\1es')
inflect.singular(/s$/, '')
inflect.singular(/es$/, '')
inflect.irregular('el', 'los')
end
Code taken from https://davidcel.is/posts/edge-rails-a-multilingual-inflector/
It looks like his gem also supports pt-BR https://github.com/davidcelis/inflections. I haven't personally tried it but it looks sane.
Hope somebody can point me at the right direction with this...
Basically, i have the locales setup and it works fine. However, i need to depending on how the user gets to the site (example_company.com, example_company.cz or example_company.de..) have slightly different content(views and layout).
I've managed to boil it down to a constant or env variable that if i was to run multiple instances of the site(1 for each country), i could set on the server so that i get the behaviour i need with 1 code base.
My question is, how are people dealing with this in general? is there any way i can serve all countries on the same instance and set some flag based on .com or .cz or whatever, that dictates which 'version' they get without effecting the url itself?
I already have the locales in the url and would prefer not to mix the two as i will have to support multiple languages for each version. For example, french and czech would still support english.. But if i go to the french one, i will only show 2 locales (french and english)...
Hope i managed to explain properly.. if not let me know and i will try again.
If you use Rails' built-in i18n support, you can easily select locales by TLD.
From the official Rails i18n guide:
One option you have is to set the locale from the domain name where your application runs. For example, we want www.example.com to load the English (or default) locale, and www.example.es to load the Spanish locale. Thus the top-level domain name is used for locale setting. This has several advantages:
The locale is an obvious part of the URL.
People intuitively grasp in which language the content will be displayed.
It is very trivial to implement in Rails.
Search engines seem to like that content in different languages lives at different, inter-linked domains.
You can implement it like this in your ApplicationController:
before_action :set_locale
def set_locale
I18n.locale = extract_locale_from_tld || I18n.default_locale
end
# Get locale from top-level domain or return nil if such locale is not available
# You have to put something like:
# 127.0.0.1 application.com
# 127.0.0.1 application.it
# 127.0.0.1 application.pl
# in your /etc/hosts file to try this out locally
def extract_locale_from_tld
parsed_locale = request.host.split('.').last
I18n.available_locales.map(&:to_s).include?(parsed_locale) ? parsed_locale : nil
end
Be sure to read the i18n guide in full. It covers how to use the built-in i18n support. A big advantage is you don't need separate views for each locale.
I am localizing an app with the default rails I18n with globalize3 as the back-end.
Is it possible to set a locale with a country code (ie :fr-CA) to fallback to its specific language (:fr) before going to the default fallback automatically? I know its possible to set each locale/country manually with
config.i18n.fallbacks = {'fr-CA' => 'fr'}
But it would be nice to not have to add each fallback manually and have this behaviour automatic.
To achieve precisely this I have an initializer with
I18n::Backend::Simple.send(:include, I18n::Backend::Fallbacks)
See the source code for more info.
Edit:
This reminds me, there is an annoying bug in the ActionView LookupContext which prevents this from working for localized views (though it works correcly for locale files). I see it still hasn't been fixed. Basically, if you have any localized views (help pages for example, which are unsuitable to store in locale files due to their length) then a fr-CA locale will not fall back to a view called help.fr.html.erb. You either have to name the file help.fr-CA.html.erb or, which is what I have done, monkeypatch the LookupContext with another initializer, sort of like this:
module ActionView
class LookupContext
# Override locale= to also set the I18n.locale. If the current I18n.config object responds
# to original_config, it means that it's has a copy of the original I18n configuration and it's
# acting as proxy, which we need to skip.
def locale=(value)
if value
config = I18n.config.respond_to?(:original_config) ? I18n.config.original_config : I18n.config
config.locale = value[0,2] # only use first part of the locale in lookups
end
super(#skip_default_locale ? I18n.locale : default_locale)
end
end
end
Another edit: Note that the patch is rather crude and breaks full locale lookups, going straight for just the language. If you need to also have fully matching views (language-REGION) you'll need to improve my code!
I've installed rails_admin gem on my localized site (3 languages) and i need administration zone (/admin) to be always in English. Any idea how to do that? Maybe I can force locale for route?
Thank you.
I haven't used rails_admin but a quick scan of it's repo would indicate it's using whatever locale is set in you app. I'm guessing you set that in a before_filter in your application.rb via one of the methods outlined in the Rails i18n guide. You'll have to make that before_filter a bit cleverer. Perhaps something like:
if self.kind_of? RailsAdmin::ApplicationController
I18n.locale = :en
else
# Your current code
end