Sha256: 63c0c1355051b91c44e22d3768f916a1049171acf8fded8aa6a9c192bfeb12c4

Contents?: true

Size: 1.55 KB

Versions: 11

Compression:

Stored size: 1.55 KB

Contents

# frozen_string_literal: true

module SensitiveDataFilter
  module Middleware
    class ParameterParser
      def self.register_parser(content_type, parse, unparse)
        parsers.unshift new(content_type, parse, unparse)
      end

      def self.parsers
        @parsers ||= DEFAULT_PARSERS.dup
      end

      def self.parser_for(content_type)
        parsers.find { |parser| parser.can_parse? content_type } || NULL_PARSER
      end

      def initialize(content_type, parse, unparse)
        @content_type = content_type
        @parse        = parse
        @unparse      = unparse
      end

      def can_parse?(content_type)
        content_type.to_s.match @content_type
      end

      def parse(params)
        @parse.call params
      end

      def unparse(params)
        @unparse.call params
      end

      NULL_PARSER = new('', ->(params) { params }, ->(params) { params })

      DEFAULT_PARSERS = [
        new('urlencoded', # e.g.: 'application/x-www-form-urlencoded'
            ->(params) { Rack::Utils.parse_query(params) },
            ->(params) { Rack::Utils.build_query(params) }),
        new('json', # e.g.: 'application/json'
            ->(params) { JsonParser.parse(params) },
            ->(params) { JsonParser.unparse(params) })
      ].freeze

      class JsonParser
        def self.parse(params)
          JSON.parse(params)
        rescue JSON::ParserError
          params
        end

        def self.unparse(params)
          JSON.unparse(params)
        rescue JSON::GeneratorError
          params
        end
      end
    end
  end
end

Version data entries

11 entries across 11 versions & 1 rubygems

Version Path
sensitive_data_filter-0.8.0 lib/sensitive_data_filter/middleware/parameter_parser.rb
sensitive_data_filter-0.7.0 lib/sensitive_data_filter/middleware/parameter_parser.rb
sensitive_data_filter-0.6.0 lib/sensitive_data_filter/middleware/parameter_parser.rb
sensitive_data_filter-0.5.0 lib/sensitive_data_filter/middleware/parameter_parser.rb
sensitive_data_filter-0.4.1 lib/sensitive_data_filter/middleware/parameter_parser.rb
sensitive_data_filter-0.4.0 lib/sensitive_data_filter/middleware/parameter_parser.rb
sensitive_data_filter-0.3.0 lib/sensitive_data_filter/middleware/parameter_parser.rb
sensitive_data_filter-0.2.4 lib/sensitive_data_filter/middleware/parameter_parser.rb
sensitive_data_filter-0.2.3 lib/sensitive_data_filter/middleware/parameter_parser.rb
sensitive_data_filter-0.2.2 lib/sensitive_data_filter/middleware/parameter_parser.rb
sensitive_data_filter-0.2.1 lib/sensitive_data_filter/middleware/parameter_parser.rb