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.
  • Loading branch information
rodrigopinto committed Jun 14, 2019
1 parent c68418e commit d9a7319
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 11 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
19 changes: 12 additions & 7 deletions src/http/params.cr
Expand Up @@ -85,12 +85,12 @@ 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
builder.add(key, value)
end
end
end
Expand All @@ -100,12 +100,12 @@ 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|
named_tuple.each do |key, value|
builder.add key.to_s, value
builder.add(key.to_s, value)
end
end
end
Expand Down Expand Up @@ -343,8 +343,8 @@ module HTTP
@first = true
end

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

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 d9a7319

Please sign in to comment.