Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@iwan
Last active March 1, 2016 14:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iwan/cdc5bed26f1eb2de8998 to your computer and use it in GitHub Desktop.
Save iwan/cdc5bed26f1eb2de8998 to your computer and use it in GitHub Desktop.
Add internationalization to a Rails project

Here described is my approach to add multiple languages to a Ruby on Rails project.

You have to edit:

  • routes file
  • the application controller
  • the view
%li.dropdown
%a.dropdown-toggle{"data-toggle" => "dropdown", :href => "#"}
= t(".#{I18n.locale}")
%b.caret
%ul.dropdown-menu
- (I18n.available_locales.map(&:to_s)-[I18n.locale.to_s]).each do |loc|
%li= link_to t(".#{loc}"), locale: loc
class ApplicationController < ActionController::Base
before_action :set_locale
...
def current_user_locale
current_account.user.locale
rescue
I18n.default_locale
end
def set_locale
loc = params[:locale]
loc = nil if !I18n.available_locales.map(&:to_s).include?(loc)
if current_account # user is logged in
if loc && loc!=current_user_locale
current_user.update_attribute(:locale, loc)
I18n.locale = loc || I18n.default_locale
else
I18n.locale = loc || current_user_locale || I18n.default_locale
end
else
I18n.locale = loc || I18n.default_locale
end
end
def default_url_options(options={})
{ locale: I18n.locale }.merge options
end
end
Gino::Application.routes.draw do
scope "(:locale)", locale: /en|it/ do
resources :groups
resources :users do
member do
get :invite
end
end
devise_scope :account do
root to: "devise/sessions#new"
get '/accounts/sign_out' => 'devise/sessions#destroy'
get '/accounts/edit' => 'devise/registrations#edit', :as => 'edit_account_registration'
put '/accounts' => 'devise/registrations#update', :as => 'account_registration'
end
devise_for :accounts
...
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment