Sha256: 7da9d081f60e64352f72885b85c8cb56fd2c465d7e72cf59886e5628c28d5cab

Contents?: true

Size: 1.59 KB

Versions: 2

Compression:

Stored size: 1.59 KB

Contents

module Graphiti
  module JsonapiSerializableExt
    # This library looks up a serializer based on the record's class name
    # This wouldn't work for us, since a model may be associated with
    # multiple resources.
    # Instead, this variable is assigned when the query is resolved
    # To ensure we always render with the *resource* serializer
    module RendererOverrides
      def _build(object, exposures, _klass)
        resource = object.instance_variable_get(:@__graphiti_resource)
        klass = object.instance_variable_get(:@__graphiti_serializer)
        klass.new(exposures.merge(object: object, resource: resource))
      end
    end

    # See above comment
    module RelationshipOverrides
      def data
        @_resources_block = proc do
          resources = yield
          if resources.nil?
            nil
          elsif resources.respond_to?(:to_ary)
            Array(resources).map do |obj|
              klass = obj.instance_variable_get(:@__graphiti_serializer)
              resource = obj.instance_variable_get(:@__graphiti_resource)
              klass.new(@_exposures.merge(object: obj, resource: resource))
            end
          else
            klass = resources.instance_variable_get(:@__graphiti_serializer)
            resource = resources.instance_variable_get(:@__graphiti_resource)
            klass.new(@_exposures.merge(object: resources, resource: resource))
          end
        end
      end
    end

    JSONAPI::Serializable::Relationship
      .send(:prepend, RelationshipOverrides)
    JSONAPI::Serializable::Renderer
      .send(:prepend, RendererOverrides)
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
graphiti-1.0.rc.23 lib/graphiti/jsonapi_serializable_ext.rb
graphiti-1.0.rc.22 lib/graphiti/jsonapi_serializable_ext.rb