Class: Porridge::KeyNormalizingSerializer
- Inherits:
-
Serializer
- Object
- Serializer
- Porridge::KeyNormalizingSerializer
- Defined in:
- lib/porridge/key_normalizing_serializer.rb
Overview
KeyNormalizingSerializer is a serializer that wraps another serializer and recursively normalizes the keys of the resulting hash to either strings or symbols.
Instance Attribute Summary collapse
-
#base ⇒ Serializer, #call
readonly
private
The base serializer whose output hash will be normalized.
-
#key_type ⇒ Symbol
readonly
private
The key type that the hash should be normalized to.
Instance Method Summary collapse
- #call(object, input, options) ⇒ Hash
-
#initialize(base, key_type: :string) ⇒ KeyNormalizingSerializer
constructor
Creates a new instance of KeyNormalizingSerializer with the given base serializer and key type.
-
#normalize_keys(hash) ⇒ Hash
private
Normalizes the keys of the given hash according to the #key_type.
Methods inherited from Serializer
Constructor Details
#initialize(base, key_type: :string) ⇒ KeyNormalizingSerializer
Creates a new instance of Porridge::KeyNormalizingSerializer with the given base serializer and key type.
16 17 18 19 20 21 |
# File 'lib/porridge/key_normalizing_serializer.rb', line 16 def initialize(base, key_type: :string) Serializer.ensure_valid!(base) @base = base @key_type = key_type super() end |
Instance Attribute Details
#base ⇒ Serializer, #call (readonly, private)
The base serializer whose output hash will be normalized
45 46 47 |
# File 'lib/porridge/key_normalizing_serializer.rb', line 45 def base @base end |
#key_type ⇒ Symbol (readonly, private)
The key type that the hash should be normalized to.
49 50 51 |
# File 'lib/porridge/key_normalizing_serializer.rb', line 49 def key_type @key_type end |
Instance Method Details
#call(object, input, options) ⇒ Hash
30 31 32 |
# File 'lib/porridge/key_normalizing_serializer.rb', line 30 def call(object, input, ) normalize_keys(base.call(object, input, )) end |
#normalize_keys(hash) ⇒ Hash (private)
Normalizes the keys of the given hash according to the #key_type. Uses ActiveSupport methods to accomplish this.
39 40 41 |
# File 'lib/porridge/key_normalizing_serializer.rb', line 39 def normalize_keys(hash) key_type == :symbol ? hash.deep_symbolize_keys : hash.deep_stringify_keys end |