Skip to content

Commit

Permalink
Add Lucky::CookieJar#[] and #[]=
Browse files Browse the repository at this point in the history
Adds easier access to cookies by adding the typical key/value syntax
for cookies get/set operations

In the future, this could potentially even implement all of Enumerable({K, V}), but
these methods are super helpful as is to provide hash-like access to cookies
  • Loading branch information
grepsedawk committed Mar 16, 2022
1 parent e637bf4 commit 3e29d03
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 0 deletions.
4 changes: 4 additions & 0 deletions spec/lucky/cookies/cookie_jar_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,15 @@ describe Lucky::CookieJar do

jar.set(:symbol_key, "symbol key")
jar.set("string_key", "string key")
jar[:another_symbol] = "symbol key"
jar["another_string"] = "string key"

jar.get(:symbol_key).should eq("symbol key")
jar.get("symbol_key").should eq("symbol key")
jar.get("string_key").should eq("string key")
jar.get(:string_key).should eq("string key")
jar[:another_symbol].should eq("symbol key")
jar["another_string"].should eq("string key")
end

it "sets and gets raw HTTP::Cookie object with indifferent access" do
Expand Down
12 changes: 12 additions & 0 deletions src/lucky/cookies/cookie_jar.cr
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,10 @@ class Lucky::CookieJar
get?(key) || raise CookieNotFoundError.new(key)
end

def [](key)
get(key)
end

def get?(key : Key) : String?
cookies[key.to_s]?.try do |cookie|
decrypt(cookie.value, cookie.name)
Expand All @@ -105,10 +109,18 @@ class Lucky::CookieJar
nil
end

def []?(key)
get?(key)
end

def set(key : Key, value : String) : HTTP::Cookie
set_raw key, encrypt(value)
end

def []=(key, value)
set(key, value)
end

def set_raw(key : Key, value : String) : HTTP::Cookie
raw_cookie = HTTP::Cookie.new(
name: key.to_s,
Expand Down

0 comments on commit 3e29d03

Please sign in to comment.