Sha256: a118c2fb3bbfcbc2ca3db30da4d3370eae84ecc9f4fdf788c764202fc5a8d014

Contents?: true

Size: 1.49 KB

Versions: 39

Compression:

Stored size: 1.49 KB

Contents

module Graphiti
  module SerializableHash
    def to_hash(fields: nil, include: {})
      {}.tap do |hash|
        fields_list = fields[jsonapi_type] if fields
        attrs = requested_attributes(fields_list).each_with_object({}) { |(k, v), h|
          h[k] = instance_eval(&v)
        }
        rels = @_relationships.select { |k, v| !!include[k] }
        rels.each_with_object({}) do |(k, v), h|
          serializers = v.send(:resources)
          attrs[k] = if serializers.is_a?(Array)
            serializers.map do |rr| # use private method to avoid array casting
              rr.to_hash(fields: fields, include: include[k])
            end
          elsif serializers.nil?
            nil
          else
            serializers.to_hash(fields: fields, include: include[k])
          end
        end

        hash[:id] = jsonapi_id
        hash.merge!(attrs) if attrs.any?
      end
    end
  end

  class HashRenderer
    def initialize(resource)
      @resource = resource
    end

    def render(options)
      serializers = options[:data]
      opts = options.slice(:fields, :include)
      to_hash(serializers, opts).tap do |hash|
        hash.merge!(options.slice(:meta)) unless options[:meta].empty?
      end
    end

    private

    def to_hash(serializers, opts)
      {}.tap do |hash|
        hash[:data] = if serializers.is_a?(Array)
          serializers.map do |s|
            s.to_hash(opts)
          end
        else
          serializers.to_hash(opts)
        end
      end
    end
  end
end

Version data entries

39 entries across 39 versions & 1 rubygems

Version Path
graphiti-1.2.28 lib/graphiti/hash_renderer.rb
graphiti-1.2.27 lib/graphiti/hash_renderer.rb
graphiti-1.2.26 lib/graphiti/hash_renderer.rb
graphiti-1.2.25 lib/graphiti/hash_renderer.rb
graphiti-1.2.21 lib/graphiti/hash_renderer.rb
graphiti-1.2.20 lib/graphiti/hash_renderer.rb
graphiti-1.2.19 lib/graphiti/hash_renderer.rb
graphiti-1.2.18 lib/graphiti/hash_renderer.rb
graphiti-1.2.17 lib/graphiti/hash_renderer.rb
graphiti-1.2.16 lib/graphiti/hash_renderer.rb
graphiti-1.2.15 lib/graphiti/hash_renderer.rb
graphiti-1.2.14 lib/graphiti/hash_renderer.rb
graphiti-1.2.13 lib/graphiti/hash_renderer.rb
graphiti-1.2.12 lib/graphiti/hash_renderer.rb
graphiti-1.2.11 lib/graphiti/hash_renderer.rb
graphiti-1.2.10 lib/graphiti/hash_renderer.rb
graphiti-1.2.9 lib/graphiti/hash_renderer.rb
graphiti-1.2.8 lib/graphiti/hash_renderer.rb
graphiti-1.2.7 lib/graphiti/hash_renderer.rb
graphiti-1.2.6 lib/graphiti/hash_renderer.rb