Skip to content

Instantly share code, notes, and snippets.

@markshiz
Created June 27, 2014 05:23
Show Gist options
  • Select an option

  • Save markshiz/6a3444a497ffe6fa90a0 to your computer and use it in GitHub Desktop.

Select an option

Save markshiz/6a3444a497ffe6fa90a0 to your computer and use it in GitHub Desktop.

Revisions

  1. markshiz created this gist Jun 27, 2014.
    42 changes: 42 additions & 0 deletions gistfile1.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,42 @@
    require 'i18n'

    module Rack
    class Locale
    def initialize(app)
    @app = app
    end

    def call(env)
    old_locale = I18n.locale

    begin
    locale = accept_locale(env) || I18n.default_locale
    locale = env['rack.locale'] = I18n.locale = locale.to_s
    status, headers, body = @app.call(env)
    headers['Content-Language'] = locale
    [status, headers, body]
    ensure
    I18n.locale = old_locale
    end
    end

    private

    # http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4
    def accept_locale(env)
    accept_langs = env["HTTP_ACCEPT_LANGUAGE"]
    return if accept_langs.nil?

    languages_and_qvalues = accept_langs.split(",").map { |l|
    l += ';q=1.0' unless l =~ /;q=\d+(?:\.\d+)?$/
    l.split(';q=')
    }

    lang = languages_and_qvalues.sort_by { |(locale, qvalue)|
    qvalue.to_f
    }.last.first

    lang == '*' ? nil : lang
    end
    end
    end