From 3780903ea4f27a936862b4173550885c8ad7ca66 Mon Sep 17 00:00:00 2001 From: Georgiy Melnikov Date: Thu, 28 Oct 2021 16:26:54 +0500 Subject: [PATCH] add symbolize keys option to deserializer --- README.md | 1 + lib/jsonapi/deserialization.rb | 8 ++++++-- spec/deserialization_spec.rb | 11 +++++++++++ 3 files changed, 18 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 8c95c08..12f7cbc 100644 --- a/README.md +++ b/README.md @@ -347,6 +347,7 @@ The `jsonapi_deserialize` helper accepts the following options: * `except`: returns exclusively attributes/relationship which are not in the list * `polymorphic`: will add and detect the `_type` attribute and class to the defined list of polymorphic relationships + * `symbolize_keys`: returns hash with symbolized keys This functionality requires support for _inflections_. If your project uses `active_support` or `rails` you don't need to do anything. Alternatively, we will diff --git a/lib/jsonapi/deserialization.rb b/lib/jsonapi/deserialization.rb index 0a9d5de..ceb7443 100644 --- a/lib/jsonapi/deserialization.rb +++ b/lib/jsonapi/deserialization.rb @@ -44,7 +44,7 @@ def jsonapi_deserialize(document, options = {}) # Transform keys and any option values. options = options.as_json - ['only', 'except', 'polymorphic'].each do |opt_name| + ['only', 'except', 'polymorphic', 'symbolize_keys'].each do |opt_name| opt_value = options[opt_name] options[opt_name] = Array(opt_value).map(&:to_s) if opt_value end @@ -77,7 +77,11 @@ def jsonapi_deserialize(document, options = {}) end end - parsed + if options['symbolize_keys'] + parsed.symbolize_keys + else + parsed + end end end end diff --git a/spec/deserialization_spec.rb b/spec/deserialization_spec.rb index b23c183..6bcba4c 100644 --- a/spec/deserialization_spec.rb +++ b/spec/deserialization_spec.rb @@ -83,5 +83,16 @@ ) end end + + + context 'with `symbolize_keys`' do + it do + expect( + jsonapi_deserialize.call( + document, symbolize_keys: true + ) + ).to match(jsonapi_deserialize.call(document).symbolize_keys) + end + end end end