diff --git a/lib/unobtrusive_flash/controller_mixin.rb b/lib/unobtrusive_flash/controller_mixin.rb index 26e316d..820b585 100644 --- a/lib/unobtrusive_flash/controller_mixin.rb +++ b/lib/unobtrusive_flash/controller_mixin.rb @@ -50,7 +50,8 @@ def sanitize_flash(flash, displayable_flash_keys) end def append_flash_to_cookie(existing_cookie, flash, unobtrusive_flash_keys) - cookie_flash = (existing_cookie && parse_cookie(existing_cookie)) || [] + cookie_flash = (existing_cookie && parse_cookie(existing_cookie)) + cookie_flash = [] unless cookie_flash.is_a? Array cookie_flash += sanitize_flash(flash, unobtrusive_flash_keys) cookie_flash.uniq.to_json end @@ -58,7 +59,7 @@ def append_flash_to_cookie(existing_cookie, flash, unobtrusive_flash_keys) def parse_cookie(existing_cookie) JSON.parse(existing_cookie) rescue JSON::JSONError - nil + [] end end end diff --git a/spec/sanitize_flash_spec.rb b/spec/sanitize_flash_spec.rb index 7f865b3..95c3534 100644 --- a/spec/sanitize_flash_spec.rb +++ b/spec/sanitize_flash_spec.rb @@ -20,6 +20,14 @@ expect(described_class.append_flash_to_cookie(nil, {:baz => 'qux'}, [:baz])).to eq('[["baz","qux"]]') end + it 'should gracefully handle non-conforming cookies' do + expect(described_class.append_flash_to_cookie('{}', {:baz => 'qux'}, [:baz])).to eq('[["baz","qux"]]') + end + + it 'should gracefully handle tampered cookies' do + expect(described_class.append_flash_to_cookie('some_invalid_json', {:baz => 'qux'}, [:baz])).to eq('[["baz","qux"]]') + end + it 'should reuse existing cookie' do expect(described_class.append_flash_to_cookie('[["foo","bar"]]', {:baz => 'qux'}, [:baz])).to eq('[["foo","bar"],["baz","qux"]]') end