Skip to content

Instantly share code, notes, and snippets.

@fieldform
Created July 25, 2013 21:04
Show Gist options
  • Save fieldform/6083758 to your computer and use it in GitHub Desktop.
Save fieldform/6083758 to your computer and use it in GitHub Desktop.
Setting locale in ApplicationController
# encoding: utf-8
class ApplicationController < ActionController::Base
protect_from_forgery
before_filter :set_locale
private
def set_locale
I18n.locale = params[:locale] ||
session[:locale] ||
extract_locale_from_host ||
extract_locale_from_accept_language_header ||
I18n.default_locale
end
def extract_locale_from_accept_language_header
unless request.env['HTTP_ACCEPT_LANGUAGE'].nil?
request.env['HTTP_ACCEPT_LANGUAGE'].scan(/^[a-z]{2}/).first
end
end
def extract_locale_from_host
case request.host
when /cn/
I18n.locale = :zh
end
end
end
require 'spec_helper'
describe ApplicationController do
controller do
def index
render :text => "Success!"
end
end
describe "extracting locale from browser language" do
it "sets locale to english" do
get :index
expect(I18n.locale).to eq(:en)
end
it "sets locale to english" do
request.env['HTTP_ACCEPT_LANGUAGE'] = 'en-us'
get :index
expect(I18n.locale).to eq(:en)
end
it "sets locale to chinese" do
request.env['HTTP_ACCEPT_LANGUAGE'] = 'zh-cn'
get :index
expect(I18n.locale).to eq(:zh)
end
end
describe "extracting locale from host" do
it "sets the locale to english" do
request.env['HTTP_HOST'] = 'www.durst.org'
get :index
expect(I18n.locale).to eq(:en)
end
it "sets the locale to chinese" do
request.env['HTTP_HOST'] = 'www.durst.cn.com'
get :index
expect(I18n.locale).to eq(:zh)
end
it "sets the locale to chinese" do
request.env['HTTP_HOST'] = 'www.durst.net.cn'
get :index
expect(I18n.locale).to eq(:zh)
end
end
describe "extracting locale from param" do
it "sets the locale to chinese" do
get :index, {:locale => "zh"}
expect(I18n.locale).to eq(:zh)
end
end
describe "extracting locale from session" do
it "sets the locale to chinese" do
session[:locale] = :zh
get :index
expect(I18n.locale).to eq(:zh)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment