Class: Porridge::KeyNormalizingSerializer

Inherits:
Serializer
  • Object
show all
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

Instance Method Summary collapse

Methods inherited from Serializer

ensure_valid!, valid?

Constructor Details

#initialize(base, key_type: :string) ⇒ KeyNormalizingSerializer

Creates a new instance of Porridge::KeyNormalizingSerializer with the given base serializer and key type.

Parameters:

  • base (Serializer, #call)

    the base serializer to wrap. Note that the output of the base serializer must be a hash.

  • key_type (Symbol) (defaults to: :string)

    the type that the keys should be normalized to. Both :string and :symbol are supported.

Raises:



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

#baseSerializer, #call (readonly, private)

The base serializer whose output hash will be normalized

Returns:



45
46
47
# File 'lib/porridge/key_normalizing_serializer.rb', line 45

def base
  @base
end

#key_typeSymbol (readonly, private)

The key type that the hash should be normalized to.

Returns:

  • (Symbol)

    either :string or :symbol.



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

Serializes the given input for the given object with the given options by delegating to the base serializer (#base) and recursively transforming the keys of the resulting hash to the appropriate type (#key_type). Note that the output of the base serializer must be a hash.

Parameters:

  • object

    the object for which to transform the input.

  • input

    the object being transformed, typically either a hash or an array.

  • options (Hash)

    a hash of “options,” which may be application specific.

Returns:

  • (Hash)

    the hash returned from the base serializer, normalized.



30
31
32
# File 'lib/porridge/key_normalizing_serializer.rb', line 30

def call(object, input, options)
  normalize_keys(base.call(object, input, options))
end

#normalize_keys(hash) ⇒ Hash (private)

Normalizes the keys of the given hash according to the #key_type. Uses ActiveSupport methods to accomplish this.

Parameters:

  • hash (Hash)

    the hash to normalize.

Returns:

  • (Hash)

    the normalized hash.



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