Skip to content

Commit

Permalink
Add QueryParser#missing_value for handling missing values + tests. (#…
Browse files Browse the repository at this point in the history
…2052)

# Conflicts:
#	lib/rack/query_parser.rb
  • Loading branch information
ioquatix committed Mar 13, 2023
1 parent 9f8ba5e commit 848c9c0
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 3 deletions.
1 change: 1 addition & 0 deletions lib/rack.rb
Expand Up @@ -41,6 +41,7 @@ module Rack
autoload :MethodOverride, "rack/method_override"
autoload :Mime, "rack/mime"
autoload :NullLogger, "rack/null_logger"
autoload :QueryParser, "rack/query_parser"
autoload :Recursive, "rack/recursive"
autoload :Reloader, "rack/reloader"
autoload :RewindableInput, "rack/rewindable_input"
Expand Down
16 changes: 13 additions & 3 deletions lib/rack/query_parser.rb
@@ -1,5 +1,7 @@
# frozen_string_literal: true

require 'uri'

module Rack
class QueryParser
DEFAULT_SEP = /[&] */n
Expand Down Expand Up @@ -111,6 +113,14 @@ def normalize_params(params, name, v, _depth=nil)
_normalize_params(params, name, v, 0)
end

# This value is used by default when a parameter is missing (nil). This
# usually happens when a parameter is specified without an `=value` part.
# The default value is an empty string, but this can be overridden by
# subclasses.
def missing_value
String.new
end

private def _normalize_params(params, name, v, depth)
raise ParamsTooDeepError if depth >= param_depth_limit

Expand Down Expand Up @@ -145,7 +155,7 @@ def normalize_params(params, name, v, _depth=nil)

return if k.empty?

v ||= String.new
v ||= missing_value

if after == ''
if k == '[]' && depth != 0
Expand Down Expand Up @@ -207,8 +217,8 @@ def params_hash_has_key?(hash, key)
true
end

def unescape(s)
Utils.unescape(s)
def unescape(string, encoding = Encoding::UTF_8)
URI.decode_www_form_component(string, encoding)
end

class Params
Expand Down
33 changes: 33 additions & 0 deletions test/spec_query_parser.rb
@@ -0,0 +1,33 @@
# frozen_string_literal: true

require_relative 'helper'

separate_testing do
require_relative '../lib/rack/query_parser'
end

describe Rack::QueryParser do
def query_parser
@query_parser ||= Rack::QueryParser.new(Rack::QueryParser::Params, 8)
end

it "has a default value" do
assert_equal "", query_parser.missing_value
end

it "can normalize values with missing values" do
query_parser.parse_nested_query("a=a").must_equal({"a" => "a"})
query_parser.parse_nested_query("a=").must_equal({"a" => ""})
query_parser.parse_nested_query("a").must_equal({"a" => ""})
end

it "can override default missing value" do
def query_parser.missing_value
nil
end

query_parser.parse_nested_query("a=a").must_equal({"a" => "a"})
query_parser.parse_nested_query("a=").must_equal({"a" => ""})
query_parser.parse_nested_query("a").must_equal({"a" => nil})
end
end

0 comments on commit 848c9c0

Please sign in to comment.