Skip to content

Commit

Permalink
Preserve empty JSON types
Browse files Browse the repository at this point in the history
The existing behavior when specifying `serializer: :json` was to store
and return an empty Hash (`{}`) for null or empty values, including
empty arrays.

This changes the encode logic to store the JSON representation of
any given value. During decode, any valid JSON string can be decoded. We
special case `nil` or `""` (empty string) to return `nil` (instead of
`{}` previously).

This could be a breaking for applications that depend on the empty hash
== nil behavior.
  • Loading branch information
justincampbell committed May 22, 2019
1 parent 414f1bd commit 43b7fd1
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 3 deletions.
5 changes: 2 additions & 3 deletions lib/vault/rails/json_serializer.rb
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,14 @@ module JSONSerializer
def self.encode(raw)
self._init!

raw = {} if raw.nil?

JSON.fast_generate(raw)
end

def self.decode(raw)
self._init!

return {} if raw.nil? || raw.empty?
return nil if raw == nil || raw == ""

JSON.parse(raw, DECODE_OPTIONS)
end

Expand Down
42 changes: 42 additions & 0 deletions spec/lib/vault/rails/json_serializer_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
require 'spec_helper'

RSpec.describe Vault::Rails::JSONSerializer do
[
nil,
false,
true,
"",
"foo",
{},
{ "foo" => "bar" },
[],
["foo", "bar"],
0,
123,
0.0,
0.123,
0xff,
123e123
].each do |object|
it "encodes and decodes #{object.inspect}" do
encoded = described_class.encode(object)
expect(encoded).to be_a(String)
decoded = described_class.decode(encoded)
expect(decoded).to eq(object)
end
end

describe ".decode" do
subject(:decoded) { described_class.decode(raw) }

context "with nil" do
let(:raw) { nil }
it { is_expected.to eq(nil) }
end

context "with an empty string" do
let(:raw) { "" }
it { is_expected.to eq(nil) }
end
end
end

0 comments on commit 43b7fd1

Please sign in to comment.