I have a multi-language website and I'm puting the language in the URL like domain.com/en/. When the user doesn't put the language in the URL I want to redirect him to the page in the main language like "domain.com/posts" to "domain.com/en/posts". Is there an easy way to do this with Sinatra?
I have more than one hundred routes. So doing this for every route is not a very good option.
get "/:locale/posts" do... end
get "/posts" do... end
Can someone help me?
Thanks
Use a before filter, somewhat like this:
set :locales, %w[en sv de]
set :default_locale, 'en'
set :locale_pattern, /^\/?(#{Regexp.union(settings.locals)})(\/.+)$/
helpers do
def locale
@locale || settings.default_locale
end
end
before do
@locale, request.path_info = $1, $2 if request.path_info =~ settings.locale_pattern
end
get '/example' do
case locale
when 'en' then 'Hello my friend!'
when 'de' then 'Hallo mein Freund!'
when 'sv' then 'Hallå min vän!'
else '???'
end
end
With the upcoming release of Sinatra, you will be able to do this:
before('/:locale/*') { @locale = params[:locale] }