Skip to content

Commit 5b86061

Browse files
authored
Merge pull request #697 from knarewski/stop-crashing-on-non-hash-json
Stop crashing on non-hash json
2 parents 95795b4 + 2314122 commit 5b86061

File tree

2 files changed

+20
-5
lines changed

2 files changed

+20
-5
lines changed

lib/split/persistence/cookie_adapter.rb

+2-1
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,8 @@ def delete_cookie_header!(header, key, value)
7070
def hash
7171
@hash ||= if cookies = @cookies[:split.to_s]
7272
begin
73-
JSON.parse(cookies)
73+
parsed = JSON.parse(cookies)
74+
parsed.is_a?(Hash) ? parsed : {}
7475
rescue JSON::ParserError
7576
{}
7677
end

spec/persistence/cookie_adapter_spec.rb

+18-4
Original file line numberDiff line numberDiff line change
@@ -14,10 +14,24 @@
1414
end
1515

1616
it "handles invalid JSON" do
17-
context.request.cookies[:split] = {
18-
value: '{"foo":2,',
19-
expires: Time.now
20-
}
17+
context.request.cookies["split"] = "{\"foo\":2,"
18+
19+
expect(subject["my_key"]).to be_nil
20+
subject["my_key"] = "my_value"
21+
expect(subject["my_key"]).to eq("my_value")
22+
end
23+
24+
it "ignores valid JSON of invalid type (integer)" do
25+
context.request.cookies["split"] = "2"
26+
27+
expect(subject["my_key"]).to be_nil
28+
subject["my_key"] = "my_value"
29+
expect(subject["my_key"]).to eq("my_value")
30+
end
31+
32+
it "ignores valid JSON of invalid type (array)" do
33+
context.request.cookies["split"] = "[\"foo\", \"bar\"]"
34+
2135
expect(subject["my_key"]).to be_nil
2236
subject["my_key"] = "my_value"
2337
expect(subject["my_key"]).to eq("my_value")

0 commit comments

Comments
 (0)