Class: Cuprum::Rails::Serializers::Json::HashSerializer
- Inherits:
-
BaseSerializer
- Object
- BaseSerializer
- Cuprum::Rails::Serializers::Json::HashSerializer
- 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
-
#call(hash, context:) ⇒ Hash
Converts the hash to JSON using the given serializers.
Methods inherited from BaseSerializer
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.
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 |