From 2c8561abb51d6de4256eb114a29422b85427a106 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Johannes=20M=C3=BCller?= Date: Mon, 25 Nov 2024 22:39:19 +0100 Subject: [PATCH] Add `Cookie#inspect` --- spec/std/http/cookie_spec.cr | 7 +++++++ src/http/cookie.cr | 15 +++++++++++++++ 2 files changed, 22 insertions(+) diff --git a/spec/std/http/cookie_spec.cr b/spec/std/http/cookie_spec.cr index d244948995b8..be4ad06a6b6b 100644 --- a/spec/std/http/cookie_spec.cr +++ b/spec/std/http/cookie_spec.cr @@ -173,6 +173,13 @@ module HTTP end end + describe "#inspect" do + it "stringifies" do + HTTP::Cookie.new("foo", "bar").inspect.should eq %(HTTP::Cookie["foo=bar"]) + HTTP::Cookie.new("x", "y", domain: "example.com", path: "/foo", expires: Time.unix(1257894000), samesite: :lax).inspect.should eq %(HTTP::Cookie["x=y; domain=example.com; path=/foo; expires=Tue, 10 Nov 2009 23:00:00 GMT; SameSite=Lax"]) + end + end + describe "#valid? & #validate!" do it "raises on invalid cookie with __Secure- prefix" do cookie = HTTP::Cookie.new "x", "", secure: false diff --git a/src/http/cookie.cr b/src/http/cookie.cr index fd0597bba575..5eabf833ad60 100644 --- a/src/http/cookie.cr +++ b/src/http/cookie.cr @@ -104,6 +104,21 @@ module HTTP end end + # Returns an unambiguous string representation of this cookie. + # + # It uses the `Set-Cookie` serialization from `#to_set_cookie_header` which + # represents the full state of the cookie. + # + # ``` + # HTTP::Cookie.new("foo", "bar").inspect # => HTTP::Cookie["foo=bar"] + # HTTP::Cookie.new("foo", "bar", domain: "example.com").inspect # => HTTP::Cookie["foo=bar; domain=example.com"] + # ``` + def inspect(io : IO) : Nil + io << "HTTP::Cookie[" + to_s.inspect(io) + io << "]" + end + # Returns a string representation of this cookie. # # It uses the `Set-Cookie` serialization from `#to_set_cookie_header` which