Skip to content

Commit

Permalink
Rename HTTP::Params.from_hash to HTTP::Params.encode and add an overload
Browse files Browse the repository at this point in the history
for NamedTuple

Also allow passing NamedTuple to the corresponding post_form overloads
on HTTP::Client
  • Loading branch information
jhass authored and asterite committed Apr 20, 2017
1 parent f40bcb3 commit 919bc4c
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 7 deletions.
12 changes: 12 additions & 0 deletions spec/std/http/params_spec.cr
Expand Up @@ -49,6 +49,18 @@ module HTTP
end
end

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

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

describe "#to_s" do
it "serializes params to http form" do
params = Params.parse("foo=bar&foo=baz&baz=qux")
Expand Down
8 changes: 4 additions & 4 deletions src/http/client.cr
Expand Up @@ -418,8 +418,8 @@ class HTTP::Client
# client = HTTP::Client.new "www.example.com"
# response = client.post_form "/", {"foo" => "bar"}
# ```
def post_form(path, form : Hash, headers : HTTP::Headers? = nil) : HTTP::Client::Response
body = HTTP::Params.from_hash(form)
def post_form(path, form : Hash(String, _) | NamedTuple, headers : HTTP::Headers? = nil) : HTTP::Client::Response
body = HTTP::Params.encode(form)
post_form path, body, headers
end

Expand All @@ -433,8 +433,8 @@ class HTTP::Client
# response.body_io.gets
# end
# ```
def post_form(path, form : Hash, headers : HTTP::Headers? = nil)
body = HTTP::Params.from_hash(form)
def post_form(path, form : Hash(String, _) | NamedTuple, headers : HTTP::Headers? = nil)
body = HTTP::Params.encode(form)
post_form(path, body, headers) do |response|
yield response
end
Expand Down
15 changes: 12 additions & 3 deletions src/http/params.cr
Expand Up @@ -69,16 +69,25 @@ module HTTP
end
end

# Creates an `HTTP::Params` instance from the key-value
# pairs of the given *hash*.
def self.from_hash(hash : Hash)
# Returns the given key value pairs as a
# url-encoded HTTP form/query.
def self.encode(hash : Hash(String, _))
build do |builder|
hash.each do |key, value|
builder.add key, value
end
end
end

# ditto
def self.encode(named_tuple : NamedTuple)
build do |builder|
named_tuple.each do |key, value|
builder.add key.to_s, value
end
end
end

# Builds an url-encoded HTTP form/query.
#
# The yielded object has an `add` method that accepts two arguments,
Expand Down

0 comments on commit 919bc4c

Please sign in to comment.