Skip to content

Commit 0e80a60

Browse files
Add stringification for HTTP::Cookies (#15246)
1 parent 0580ff2 commit 0e80a60

File tree

2 files changed

+62
-0
lines changed

2 files changed

+62
-0
lines changed

spec/std/http/cookie_spec.cr

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -751,4 +751,39 @@ module HTTP
751751
cookies.to_h.should_not eq(cookies_hash)
752752
end
753753
end
754+
755+
describe "#to_s" do
756+
it "stringifies" do
757+
cookies = HTTP::Cookies{
758+
HTTP::Cookie.new("foo", "bar"),
759+
HTTP::Cookie.new("x", "y", domain: "example.com", path: "/foo", expires: Time.unix(1257894000), samesite: :lax),
760+
}
761+
762+
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"})
763+
end
764+
end
765+
766+
describe "#inspect" do
767+
it "stringifies" do
768+
cookies = HTTP::Cookies{
769+
HTTP::Cookie.new("foo", "bar"),
770+
HTTP::Cookie.new("x", "y", domain: "example.com", path: "/foo", expires: Time.unix(1257894000), samesite: :lax),
771+
}
772+
773+
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"})
774+
end
775+
end
776+
777+
describe "#pretty_print" do
778+
it "stringifies" do
779+
cookies = HTTP::Cookies{
780+
HTTP::Cookie.new("foo", "bar"),
781+
HTTP::Cookie.new("x", "y", domain: "example.com", path: "/foo", expires: Time.unix(1257894000), samesite: :lax),
782+
}
783+
cookies.pretty_inspect.should eq <<-CRYSTAL
784+
HTTP::Cookies{"foo=bar",
785+
"x=y; domain=example.com; path=/foo; expires=Tue, 10 Nov 2009 23:00:00 GMT; SameSite=Lax"}
786+
CRYSTAL
787+
end
788+
end
754789
end

src/http/cookie.cr

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -539,5 +539,32 @@ module HTTP
539539
def to_h : Hash(String, Cookie)
540540
@cookies.dup
541541
end
542+
543+
# Returns a string representation of this cookies list.
544+
#
545+
# It uses the `Set-Cookie` serialization from `Cookie#to_set_cookie_header` which
546+
# represents the full state of the cookie.
547+
#
548+
# ```
549+
# HTTP::Cookies{
550+
# HTTP::Cookie.new("foo", "bar"),
551+
# HTTP::Cookie.new("foo", "bar", domain: "example.com"),
552+
# }.to_s # => "HTTP::Cookies{\"foo=bar\", \"foo=bar; domain=example.com\"}"
553+
# ```
554+
def to_s(io : IO)
555+
io << "HTTP::Cookies{"
556+
join(io, ", ") { |cookie| cookie.to_set_cookie_header.inspect(io) }
557+
io << "}"
558+
end
559+
560+
# :ditto:
561+
def inspect(io : IO)
562+
to_s(io)
563+
end
564+
565+
# :ditto:
566+
def pretty_print(pp) : Nil
567+
pp.list("HTTP::Cookies{", self, "}") { |elem| pp.text(elem.to_set_cookie_header.inspect) }
568+
end
542569
end
543570
end

0 commit comments

Comments
 (0)