Class: Cuprum::Rails::Serializers::Json::HashSerializer

Inherits:
BaseSerializer
  • Object
show all
Defined in:
lib/cuprum/rails/serializers/json/hash_serializer.rb

Overview

Converts Hash data structures to JSON based on configured serializers.

Instance Method Summary collapse

Methods inherited from BaseSerializer

instance

Instance Method Details

#call(hash, context:) ⇒ Hash

Converts the hash to JSON using the given serializers.

First, #call finds the best serializer from the :serializers Hash for each value in the Hash. This is done by walking up the object class’s ancestors to find the closest ancestor which is a key in the :serializers Hash. The corresponding value is then called with the object, and the results are combined into a new Hash and returned.

Parameters:

  • hash (Hash<String, Object>)

    The hash to convert to JSON.

  • context (Cuprum::Rails::Serializers::Context)

    The serialization context, which includes the configured serializers for attributes or collection items.

Returns:

  • (Hash)

    a JSON-compatible representation of the hash.

Raises:

  • UndefinedSerializerError if there is no matching serializer for any of the values in the hash.



26
27
28
29
30
31
32
33
34
# File 'lib/cuprum/rails/serializers/json/hash_serializer.rb', line 26

def call(hash, context:)
  unless hash.is_a?(Hash) && hash.keys.all? { |key| key.is_a?(String) }
    raise ArgumentError, 'object must be a Hash with String keys'
  end

  hash.each.with_object({}) do |(key, value), mapped|
    mapped[key] = super(value, context: context)
  end
end