Skip to content

Instantly share code, notes, and snippets.

@fnordfish
Created December 10, 2012 10:39
Show Gist options
  • Save fnordfish/4249870 to your computer and use it in GitHub Desktop.
Save fnordfish/4249870 to your computer and use it in GitHub Desktop.
Padrino Autolocale with "smart" redirect to default locale
module Padrino
module Contrib
##
# This extension give to padrino the ability to change
# their locale inspecting.
#
# ==== Usage
#
# class MyApp < Padrino::Application
# register AutoLocale
# set :locales, [:en, :ru, :de] # First locale is the default locale
# end
#
# # view.haml
# =link_to "View this page in RU Version", switch_to_lang(:ru)
#
# So when we call an url like: /ru/blog/posts this extension set for you :ru as I18n.locale
#
module AutoLocale
def self.registered(app)
app.helpers Padrino::Contrib::AutoLocale::Helpers
app.extend ClassMethods
app.set :locales, [:en]
app.before do
if request.path_info =~ /^\/(#{settings.locales.join('|')})\b/
I18n.locale = $1.to_sym
elsif I18n.locale && settings.locales.include?(I18n.locale)
redirect "/#{I18n.locale}#{request.path_info}"
else
lang = I18n.locale = settings.locales[0]
url = if request.path_info =~ /^\/[a-z]{2}(_[A-Z]{2})?\b/
request.path_info.sub(/^\/[a-z]{2}(_[A-Z]{2})?\b/, "/#{lang}")
else
"/#{lang}#{request.path_info}"
end
redirect url
end
end
def self.padrino_route_added(route, verb, path, args, options, block)
route.instance_variable_set(:@original_path, "/:lang#{route.original_path}") unless route.original_path =~/:lang/
end
end
end # AutoLocale
end # Contrib
end # Padrino
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment