<commit_before>require "rack/accept"

module Rack
  class LocaleRootRedirect
    VERSION = "0.1"

    def initialize(app, locales = {})
      @locales = locales
      @available_locales = locales.keys.map(&:to_s)
      @default_locale = @available_locales.first
      @app = app
    end

    def call(env)
      status, headers, response = @app.call(env)

      if match_data = %r[\A/(?<query_string>\?.*|\Z)].match(env['PATH_INFO'])
        language_matcher = env['rack-accept.request'].language
        language_matcher.first_level_match = true
        redirect_lang = language_matcher.best_of(@available_locales) || @default_locale

        status = 302
        query_string = env['QUERY_STRING'] ? "?#{env['QUERY_STRING']}" : ''
        headers["Location"] = @locales[redirect_lang.to_sym] + query_string
      end

      [status, headers, response]
    end
  end
end<commit_msg>Add #root_request?<commit_after>require "rack/accept"

module Rack
  class LocaleRootRedirect
    VERSION = "0.1"

    def initialize(app, locales = {})
      @locales = locales
      @available_locales = locales.keys.map(&:to_s)
      @default_locale = @available_locales.first
      @app = app
    end

    def call(env)
      status, headers, response = @app.call(env)

      if root_request?(env)
        language_matcher = env['rack-accept.request'].language.tap { |m| m.first_level_match = true }
        redirect_lang = language_matcher.best_of(@available_locales) || @default_locale

        status = 302
        query_string = env['QUERY_STRING'] ? "?#{env['QUERY_STRING']}" : ''
        headers["Location"] = @locales[redirect_lang.to_sym] + query_string
      end

      [status, headers, response]
    end

  protected

    def root_request?(env)
      %r[\A/(?<query_string>\?.*|\Z)].match(env['PATH_INFO'])
    end
  end
end
{'fraction_non_alphanumeric': 0.13509060955518945, 'fraction_numerical': 0.0054914881933003845, 'mean_word_length': 3.076062639821029, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5373774', 'n_tokens_mistral': 614, 'n_tokens_neox': 592, 'n_words': 107}