Sha256: 66e3b61ef0b758cc64dc50a1bc081eff786078dd207b4c58de60005f6936579c

Contents?: true

Size: 1.3 KB

Versions: 4

Compression:

Stored size: 1.3 KB

Contents

require 'i18n'
require 'configatron'

module Lookout::Rack::Utils
  module I18n
    ::I18n.default_locale = configatron.default_locale

    def t(*args)
      ::I18n.t(*args)
    end

    def current_locale
      return @locale unless @locale.nil?

      accepted_languages.each do |lang, quality|
        if configatron.locales.include?(lang)
          @locale = lang
          return @locale
        end
      end

      # Just fallback to what we have set for the default
      @locale = configatron.default_locale
      return @locale
    end

    # We expect this to be called in a Rack request, but it will default to
    # returning [] if not.
    def accepted_languages
      accepted = defined?(request.env) && request.env['HTTP_ACCEPT_LANGUAGE']
      return [] if accepted.nil?

      # parse Accept-Language
      accepted = accepted.split(',')
      accepted = accepted.map { |l| l.strip.split(";") }
      accepted = accepted.map { |l|
        # en-US -> :en
        lang = l[0].split('-').first.downcase.to_sym

        if (l.size == 2)
          # quality present
          [lang, l[1].sub(/^q=/, "").to_f ]
        else
          # no quality specified => quality == 1
          [ lang, 1.0 ]
        end
      }
      # sort by quality
      accepted.sort { |left, right| right[1] <=> left[1] }
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
lookout-rack-utils-1.2.3 lib/lookout/rack/utils/i18n.rb
lookout-rack-utils-1.2.2 lib/lookout/rack/utils/i18n.rb
lookout-rack-utils-1.2.1 lib/lookout/rack/utils/i18n.rb
lookout-rack-utils-1.2.0 lib/lookout/rack/utils/i18n.rb