Sha256: e733c33f31c7803d3ecc12e6760b2c00a077f636fddb600a13cf059ed98eade8

Contents?: true

Size: 1.2 KB

Versions: 3

Compression:

Stored size: 1.2 KB

Contents

module Chronicle
  module Serialization
    class JSONAPISerializer < Chronicle::Serialization::Serializer
      def serializable_hash
        { data: serialize_record(@record) }
      end

      private

      def serialize_record(record)
        identifier_hash(record).merge({
          attributes: attribute_hash(record),
          relationships: associations_hash(record),
          meta: record.meta
        })
      end

      def identifier_hash(record)
        {
          type: record.type.to_s,
          id: record.id
        }.compact
      end

      def attribute_hash(record)
        record.attribute_properties.compact.transform_values do |v|
          if v.is_a?(Chronicle::Serialization::Record)
            serialize_record(v)
          else
            v
          end
        end
      end

      def associations_hash(record)
        record.association_properties.compact.to_h do |k, v|
          if v.is_a?(Array)
            [k, { data: v.map { |record| serialize_record(record) } }]
          elsif v.is_a?(Chronicle::Serialization::Record)
            [k, { data: serialize_record(v) }]
          else
            # [k, { data: v }]
            [k, v]
          end
        end
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
chronicle-core-0.3.2 lib/chronicle/serialization/jsonapi_serializer.rb
chronicle-core-0.3.1 lib/chronicle/serialization/jsonapi_serializer.rb
chronicle-core-0.3.0 lib/chronicle/serialization/jsonapi_serializer.rb