Skip to content

Commit

Permalink
Adds support to HTTP::Params.encode encode a key with an arrays of …
Browse files Browse the repository at this point in the history
…values. (crystal-lang#7862)
  • Loading branch information
rodrigopinto authored and dnamsons committed Jan 10, 2020
1 parent 5bbd3b0 commit fbcd33b
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 8 deletions.
8 changes: 4 additions & 4 deletions spec/std/http/params_spec.cr
Expand Up @@ -57,13 +57,13 @@ module HTTP

describe ".encode" do
it "builds from hash" do
encoded = Params.encode({"foo" => "bar", "baz" => "quux"})
encoded.should eq("foo=bar&baz=quux")
encoded = Params.encode({"foo" => "bar", "baz" => ["quux", "quuz"]})
encoded.should eq("foo=bar&baz=quux&baz=quuz")
end

it "builds from named tuple" do
encoded = Params.encode({foo: "bar", baz: "quux"})
encoded.should eq("foo=bar&baz=quux")
encoded = Params.encode({foo: "bar", baz: ["quux", "quuz"]})
encoded.should eq("foo=bar&baz=quux&baz=quuz")
end
end

Expand Down
14 changes: 10 additions & 4 deletions src/http/params.cr
Expand Up @@ -85,9 +85,9 @@ module HTTP
# ```
# require "http/params"
#
# HTTP::Params.encode({"foo" => "bar", "baz" => "qux"}) # => "foo=bar&baz=qux"
# HTTP::Params.encode({"foo" => "bar", "baz" => ["quux", "quuz"]}) # => "foo=bar&baz=quux&baz=quuz"
# ```
def self.encode(hash : Hash(String, String))
def self.encode(hash : Hash(String, String | Array(String)))
build do |builder|
hash.each do |key, value|
builder.add key, value
Expand All @@ -100,7 +100,7 @@ module HTTP
# ```
# require "http/params"
#
# HTTP::Params.encode({foo: "bar", baz: "qux"}) # => "foo=bar&baz=qux"
# HTTP::Params.encode({foo: "bar", baz: ["quux", "quuz"]}) # => "foo=bar&baz=quux&baz=quuz"
# ```
def self.encode(named_tuple : NamedTuple)
build do |builder|
Expand Down Expand Up @@ -344,7 +344,7 @@ module HTTP
end

# Adds a key-value pair to the params being built.
def add(key, value)
def add(key, value : String?)
@io << '&' unless @first
@first = false
URI.escape key, @io
Expand All @@ -353,6 +353,12 @@ module HTTP
self
end

# Adds all of the given *values* as key-value pairs to the params being built.
def add(key, values : Array)
values.each { |value| add(key, value) }
self
end

def to_s(io : IO) : Nil
io << @io.to_s
end
Expand Down

0 comments on commit fbcd33b

Please sign in to comment.