<commit_before>require "json"

module BetterErrors
  class Middleware
    def initialize(app, handler = ErrorPage)
      @app      = app
      @handler  = handler
    end
    
    def call(env)
      if env["REQUEST_PATH"] =~ %r{\A/__better_errors/(?<oid>\d+)/(?<method>\w+)\z}
        internal_call env, $~
      else
        app_call env
      end
    end
    
  private
    def app_call(env)
      @app.call env
    rescue Exception => ex
      @error_page = @handler.new ex, env
      [500, { "Content-Type" => "text/html; charset=utf-8" }, [@error_page.render]]
    end
  
    def internal_call(env, opts)
      if opts[:oid].to_i != @error_page.object_id
        return [200, { "Content-Type" => "text/plain; charset=utf-8" }, [JSON.dump(error: "Session expired")]]
      end
      
      response = @error_page.send("do_#{opts[:method]}", JSON.parse(env["rack.input"].read))
      [200, { "Content-Type" => "text/plain; charset=utf-8" }, [JSON.dump(response)]]
    end
  end<commit_msg>use PATH_INFO instead of REQUEST_PATH (closes #4)<commit_after>require "json"

module BetterErrors
  class Middleware
    def initialize(app, handler = ErrorPage)
      @app      = app
      @handler  = handler
    end
    
    def call(env)
      if env["PATH_INFO"] =~ %r{/__better_errors/(?<oid>\d+)/(?<method>\w+)}
        internal_call env, $~
      else
        app_call env
      end
    end
    
  private
    def app_call(env)
      @app.call env
    rescue Exception => ex
      @error_page = @handler.new ex, env
      [500, { "Content-Type" => "text/html; charset=utf-8" }, [@error_page.render]]
    end
  
    def internal_call(env, opts)
      if opts[:oid].to_i != @error_page.object_id
        return [200, { "Content-Type" => "text/plain; charset=utf-8" }, [JSON.dump(error: "Session expired")]]
      end
      
      response = @error_page.send("do_#{opts[:method]}", JSON.parse(env["rack.input"].read))
      [200, { "Content-Type" => "text/plain; charset=utf-8" }, [JSON.dump(response)]]
    end
  end
{'fraction_non_alphanumeric': 0.15831265508684864, 'fraction_numerical': 0.01240694789081886, 'mean_word_length': 2.580817051509769, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 15, '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': '7534281', 'n_tokens_mistral': 721, 'n_tokens_neox': 693, 'n_words': 145}