10.04.2017 Views

Rails I18n – Seven Best Practices That You Should Know About

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

<strong>Rails</strong> Internationalization (<strong>I18n</strong>) - <strong>Seven</strong> <strong>Best</strong> <strong>Practices</strong> <strong>That</strong> <strong>You</strong> <strong>Should</strong> <strong>Know</strong> <strong>About</strong><br />

available_locales() returns an array with symbols, so here we convert them to strings and then<br />

check whether the requested language code was found inside. <strong>You</strong> can read more on this<br />

technique at our ​Setting and Managing Locales in <strong>Rails</strong> <strong>I18n</strong>​ article.<br />

Utilize Localized Views<br />

Some developers tend to place all translations inside the YAML files regardless of their length<br />

and complexity. In some cases, however, that’s not really convenient. Suppose you have a page<br />

that looks totally different depending on the chosen language. Of course, you ​might do<br />

something like this:<br />

1<br />

<br />

2<br />

3<br />

<br />

4<br />

5<br />

<br />

Then you would have to define these keys, but the corresponding messages are too large:<br />

1<br />

2<br />

3<br />

welcome: 'Welcome!'<br />

special_offer: 'Here is our cool special offer! And then more text here...'<br />

about: 'Long text goes here.... and more text... even more...'<br />

Alternatively, you may take advantage of ​HTML translations but that’s not going to help a lot <strong>–</strong><br />

you still have long messages that are hard to maintain.<br />

What you can do instead, is stick with the ​localized views that allows you to store totally<br />

different content for each locale. They are employed by simply prefixing your views with the<br />

locale’s code, for example ​about.ru.html.erb and ​about.en.html.erb​. <strong>Rails</strong> will render the proper<br />

view automatically depending on the value returned by the ​<strong>I18n</strong>.locale()​ method.<br />

phraseapp.com | sales@phraseapp.com | +49-40-357-187-76 | twitter.com/phraseapp | facebook.com/phraseapp | linkedin.com/company/phraseapp

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!