<commit_before>module Rack::JSON
  class Filter
    include Rack::JSON::EndPoint

    def initialize(app, options)
      @app = app
      @collections = options[:collections]
      @filters = options[:filters]
      @methods = options[:methods]
    end

    def call(env)
      request = Rack::JSON::Request.new(env)
      if bypass_path?(request) || bypass_method?(request)
        @app.call(env)
      else
        apply_filters(request)
      end
    end

    private

    def append_filters_to_document_in request
      document = Rack::JSON::Document.create(request.json)
      document.add_attributes(request.session.reject { |key, value| !@filters.include?(key.to_sym) })
      request.set_body(document.to_json)
    end

    def apply_filters(request)
      @filters.each do |filter|
        return pre_condition_not_met unless request.session.keys.include? filter.to_s
        request.add_query_param "[?#{filter}=#{request.session[filter.to_s]}]"
      end
      append_filters_to_document_in request if request.post? || request.put?
      @app.call(request.env)<commit_msg>Better error handling if the :filters attr is forgotten<commit_after>module Rack::JSON
  class Filter
    include Rack::JSON::EndPoint

    def initialize(app, options)
      @app = app
      @collections = options[:collections]
      @filters = options[:filters]
      @methods = options[:methods]
    end

    def call(env)
      request = Rack::JSON::Request.new(env)
      if bypass_path?(request) || bypass_method?(request)
        @app.call(env)
      else
        apply_filters(request)
      end
    end

    private

    def append_filters_to_document_in request
      document = Rack::JSON::Document.create(request.json)
      document.add_attributes(request.session.reject { |key, value| !@filters.include?(key.to_sym) })
      request.set_body(document.to_json)
    end

    def apply_filters(request)
      raise 'no filters given!' if @filters.nil?
      @filters.each do |filter|
        return pre_condition_not_met unless request.session.keys.include? filter.to_s
        request.add_query_param "[?#{filter}=#{request.session[filter.to_s]}]"
      end
      append_filters_to_document_in request if request.post? || request.put?
      @app.call(request.env)
{'fraction_non_alphanumeric': 0.1111111111111111, 'fraction_numerical': 0.0, 'mean_word_length': 3.200743494423792, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, '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': '1167028', 'n_tokens_mistral': 691, 'n_tokens_neox': 682, 'n_words': 135}