Skip to content

Commit

Permalink
Add stringification for HTTP::Cookies (#15246)
Browse files Browse the repository at this point in the history
  • Loading branch information
straight-shoota authored Dec 4, 2024
1 parent 0580ff2 commit 0e80a60
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 0 deletions.
35 changes: 35 additions & 0 deletions spec/std/http/cookie_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -751,4 +751,39 @@ module HTTP
cookies.to_h.should_not eq(cookies_hash)
end
end

describe "#to_s" do
it "stringifies" do
cookies = HTTP::Cookies{
HTTP::Cookie.new("foo", "bar"),
HTTP::Cookie.new("x", "y", domain: "example.com", path: "/foo", expires: Time.unix(1257894000), samesite: :lax),
}

cookies.to_s.should eq %(HTTP::Cookies{"foo=bar", "x=y; domain=example.com; path=/foo; expires=Tue, 10 Nov 2009 23:00:00 GMT; SameSite=Lax"})
end
end

describe "#inspect" do
it "stringifies" do
cookies = HTTP::Cookies{
HTTP::Cookie.new("foo", "bar"),
HTTP::Cookie.new("x", "y", domain: "example.com", path: "/foo", expires: Time.unix(1257894000), samesite: :lax),
}

cookies.inspect.should eq %(HTTP::Cookies{"foo=bar", "x=y; domain=example.com; path=/foo; expires=Tue, 10 Nov 2009 23:00:00 GMT; SameSite=Lax"})
end
end

describe "#pretty_print" do
it "stringifies" do
cookies = HTTP::Cookies{
HTTP::Cookie.new("foo", "bar"),
HTTP::Cookie.new("x", "y", domain: "example.com", path: "/foo", expires: Time.unix(1257894000), samesite: :lax),
}
cookies.pretty_inspect.should eq <<-CRYSTAL
HTTP::Cookies{"foo=bar",
"x=y; domain=example.com; path=/foo; expires=Tue, 10 Nov 2009 23:00:00 GMT; SameSite=Lax"}
CRYSTAL
end
end
end
27 changes: 27 additions & 0 deletions src/http/cookie.cr
Original file line number Diff line number Diff line change
Expand Up @@ -539,5 +539,32 @@ module HTTP
def to_h : Hash(String, Cookie)
@cookies.dup
end

# Returns a string representation of this cookies list.
#
# It uses the `Set-Cookie` serialization from `Cookie#to_set_cookie_header` which
# represents the full state of the cookie.
#
# ```
# HTTP::Cookies{
# HTTP::Cookie.new("foo", "bar"),
# HTTP::Cookie.new("foo", "bar", domain: "example.com"),
# }.to_s # => "HTTP::Cookies{\"foo=bar\", \"foo=bar; domain=example.com\"}"
# ```
def to_s(io : IO)
io << "HTTP::Cookies{"
join(io, ", ") { |cookie| cookie.to_set_cookie_header.inspect(io) }
io << "}"
end

# :ditto:
def inspect(io : IO)
to_s(io)
end

# :ditto:
def pretty_print(pp) : Nil
pp.list("HTTP::Cookies{", self, "}") { |elem| pp.text(elem.to_set_cookie_header.inspect) }
end
end
end

0 comments on commit 0e80a60

Please sign in to comment.