10.04.2017 Views

Rails I18n – Seven Best Practices That You Should Know About

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

<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 />

Employ “Lazy” Lookups<br />

One cool thing about <strong>I18n</strong> in <strong>Rails</strong> is that when naming and nesting your keys properly, you can<br />

write less code inside the views and controllers. How is that possible? Well, let’s say you have a<br />

view called ​about.html.erb stored inside the ​app/views/pages folder. Inside you wish to display<br />

the page’s title:<br />

1 <br />

However, this code can be as simple as:<br />

1 <br />

In order for this to work, you need to nest the ​title​ key under the ​pages.about​scope:<br />

1<br />

2<br />

3<br />

pages:<br />

about:<br />

title: '<strong>About</strong> us'<br />

This works, because the scope is written properly: it contains the folder’s and the view’s name<br />

(​pages​ and ​about​ respectively).<br />

The same approach works for controllers, so having the following translation in place:<br />

1<br />

orders:<br />

2<br />

3<br />

create:<br />

success: '<strong>You</strong>r order is created!'<br />

<strong>You</strong> may create a flash message easily:<br />

1<br />

2<br />

3<br />

4<br />

5<br />

6<br />

class OrdersController < ApplicationController<br />

def create<br />

# ...<br />

flash[:success] = t(:success)<br />

end<br />

end<br />

It’s really convenient, so don’t be lazy to employ the “lazy” lookups!<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!