Skip to content

Instantly share code, notes, and snippets.

@lucatironi
Created November 14, 2012 08:48
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 lucatironi/4071034 to your computer and use it in GitHub Desktop.
Save lucatironi/4071034 to your computer and use it in GitHub Desktop.
class ApplicationController < ActionController::Base
before_filter :set_locale
protect_from_forgery
def set_locale
logger.debug "* Accept-Language: #{request.env['HTTP_ACCEPT_LANGUAGE']}"
I18n.locale = current_user ? current_user.locale : (params[:locale] || extract_locale_from_accept_language_header || I18n.default_locale)
logger.debug "* Locale set to '#{I18n.locale}'"
end
def default_url_options(options={})
logger.debug "* default_url_options is passed options: #{options.inspect}\n"
if current_user
{ :locale => current_user.locale }
else
{ :locale => I18n.locale }
end
end
private
def extract_locale_from_accept_language_header
if request.env['HTTP_ACCEPT_LANGUAGE']
locale = request.env['HTTP_ACCEPT_LANGUAGE'].scan(/^[a-z]{2}/).first
locale.match(/^(en|it)$/) ? locale : I18n.default_locale
else
I18n.default_locale
end
end
end
Feature: Auto Localization
In order to reach the widest audience for my site
A visitor of the site
Should be able to read the content in her/his language
Scenario: Italian visitor visit the homepage
Given I am an italian visitor (it;it-IT)
When I visit the homepage
Then I should read the content in italian (it)
Scenario: English visitor visit the homepage
Given I am an english visitor (en;en-US)
When I visit the homepage
Then I should read the content in english (en)
Scenario: Foreign visitor visit the homepage
Given I am an svedish visitor (sv;sv-SV)
When I visit the homepage
Then I should read the content in italian (it)
Given /^I am an (.*?) visitor \((.*?)\)$/ do |nationality, locale|
page.driver.header 'Accept-Language', locale
end
When /^I visit the homepage$/ do
visit root_path
end
Then /^I should read the content in (.*?) \((.*?)\)$/ do |nationality, locale|
page.should have_content I18n.t("pages.home.claim", :locale => locale)
end
MyApp::Application.routes.draw do
scope "(:locale)", :locale => /en|it/ do
# resources
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment