tutorials. WEB DEVELOPMENT

Header

Multilingual Application with domain switch in Rails

For my first tutorial, I have decided to share what I have done in a couple of projects that were Multilingual(in more than one language). That can easily be achieved using internationalization gem which handles the translations but then the tricky part comes in when you want two different domains for each lingual site. You can grab the code here Github Repo

Getting started

Lets get started by creating a new app. I'll call it LingualSwitch

$ rails new LingualSwitch

So for design, we'll use bootstrap. Let's set these two gems that we'll used in addition to the default ones
As stated i18n will provide internationalization and localization solution for the app. Let's install those gems by running

$ bundle install

Then add our home page

rails g controller StaticPages home

Let's set our home page as the root path by adding the following in our routes.rb file in config directory
routes.rb
Our home page is still blank. We can fill it with the following
home.html.erb
Create _nav partial holding navigation contents as follows
_nav.html.erb
Then tweak our application.html.erb to render the navigation
application.html.erb
When you refresh the page, you should get see the following
Initial home page English page

Adding switching menu

Rails adds all .yml files from the config/locales directory to translations load path automatically. We'll set our translations from this directory. There's the default en.yml which will hold our English translations. We'll add fr.yml that will hold our French translations. The result
en.yml
fr.yml
Then we'll call these translations in home.htm.erb by changing it to the following
home.html.erb
You'll then need to edit your local /etc/hosts to add out custom domains. Open the file with your favorite text editor, in my case I'll use sublime
subl /etc/hosts Then add the following /etc/hosts

Setting locale from domain name

We want lingualswitch.en to load English version and lingualinterrupteur.fr the French version of the application. We'll use the top-level domain name for locale setting by adding the following to our ApplicationController
application_controller.rb
Finally, we'll adding the switching menu to our _nav partial
English page English page
French page English page
Conclution: To get this working in production, you'll need to add both domains to your DNS.
Speed Your Rails App with Model

By Victor Areba

Blog pic
I am a passionate Rubyist. This is a platform where I share what I have learned over the years in matters Ruby, Rails, JavaScript and other related technologies. I also write non technical stuff particulary creative writing here Inkulumo. I enjoy swimming and watching movies.

0 comments

Login to post your comment