Sha256: a3ff98644b8c1c9293429dd04e05b7d30bbb4c1727f2cce69bfc8207946ba8c3

Contents?: true

Size: 1.54 KB

Versions: 1

Compression:

Stored size: 1.54 KB

Contents

require 'ivy/serializers/formats/json'

module Ivy
  module Serializers
    module Formats
      class JSONAPI < JSON
        def attribute(key, value)
          value = coerce_id(value) if key == :id
          super
        end

        def belongs_to(name, resource, options={})
          @hash_gen.store_object(name) { linkage(resource) }
        end

        def has_many(name, resources, options={})
          @hash_gen.store_object(name) { linkages(resources) }
        end

        def linked(document)
          @hash_gen.store_object(:included) { super }
        end

        def links(document)
          @hash_gen.store_object(:links) { super }
        end

        def primary_resource(primary_resource_name, primary_resource)
          @hash_gen.store_object(:data) { resource(primary_resource) }
        end

        def resource(resource)
          super
          type(:type, resource)
        end

        private

        def coerce_id(id)
          id.to_s
        end

        def extract_id(resource)
          coerce_id(super)
        end

        def linkage(resource)
          @hash_gen.store_object(:linkage) { linkage_object(resource) }
        end

        def linkage_object(resource)
          id(:id, resource)
          type(:type, resource)
        end

        def linkages(resources)
          @hash_gen.store_array(:linkage) { linkage_objects(resources) }
        end

        def linkage_objects(resources)
          resources.each { |resource| @hash_gen.push_object { linkage_object(resource) } }
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
ivy-serializers-0.1.0 lib/ivy/serializers/formats/json_api.rb