Sha256: 25717afebe84f3172bf2e4a8739e8ed3b1a8eb3da15491ee871eedba8a03e704

Contents?: true

Size: 1.5 KB

Versions: 2

Compression:

Stored size: 1.5 KB

Contents

require 'set'

module Ivy
  module Serializers
    module Documents
      class Document
        def initialize(serializer, primary_resource_name, primary_resource)
          @serializer = serializer
          @primary_resource_name = primary_resource_name
          @primary_resource = primary_resource
          @linked_resources = Hash.new { |hash, klass| hash[klass] = Set.new }
        end

        def belongs_to(name, resource, options={})
          link(resource) if options[:embed_in_root]
        end

        def generate(generator)
          generator.document(self)
        end

        def generate_linked(generator)
          generator.linked(self) unless @linked_resources.empty?
        end

        def generate_linked_resources(generator)
          @linked_resources.each_pair { |klass, resources| generator.linked_resources(klass, resources) }
        end

        def generate_links(generator, resource)
          @serializer.links(generator, resource)
        end

        def generate_resource(generator, resource)
          @serializer.resource(generator, resource)
          generator.links(resource)
        end

        def has_many(name, resources, options={})
          link_many(resources) if options[:embed_in_root]
        end

        private

        def link(resource)
          @serializer.links(self, resource) if @linked_resources[resource.class].add?(resource)
        end

        def link_many(resources)
          resources.each { |resource| link(resource) }
        end
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
ivy-serializers-0.2.0 lib/ivy/serializers/documents/document.rb
ivy-serializers-0.1.0 lib/ivy/serializers/documents/document.rb