Sha256: d0ef29112b35a07dc381ab48c02a28f87998dc21ddaf1b8922edb1e024bf3951

Contents?: true

Size: 1.61 KB

Versions: 22

Compression:

Stored size: 1.61 KB

Contents

module Graphiti
  class Renderer
    CONTENT_TYPE = 'application/vnd.api+json'

    attr_reader :proxy, :options

    def initialize(proxy, options)
      @proxy = proxy
      @options = options
    end

    def records
      @records ||= @proxy.data
    end

    def to_jsonapi
      render(self.class.jsonapi_renderer).to_json
    end

    def to_json
      render(self.class.hash_renderer(@proxy)).to_json
    end

    def to_xml
      render(self.class.hash_renderer(@proxy)).to_xml(root: :data)
    end

    def self.jsonapi_renderer
      @jsonapi_renderer ||= JSONAPI::Serializable::Renderer
        .new(JSONAPI::Renderer.new)
    end

    def self.hash_renderer(proxy)
      implementation = Graphiti::HashRenderer.new(proxy.resource)
      JSONAPI::Serializable::Renderer.new(implementation)
    end

    private

    def render(renderer)
      notify do
        options[:fields] = proxy.fields
        options[:expose] ||= {}
        options[:expose][:extra_fields] = proxy.extra_fields
        options[:expose][:proxy] = proxy
        options[:include] = proxy.include_hash
        options[:meta] ||= {}
        options[:meta].merge!(stats: proxy.stats) unless proxy.stats.empty?
        renderer.render(records, options)
      end
    end

    # TODO: more generic notification pattern
    # Likely comes out of debugger work
    def notify
      if defined?(ActiveSupport::Notifications)
        opts = [
          'render.graphiti',
          records: records,
          options: options
        ]
        ActiveSupport::Notifications.instrument(*opts) do
          yield
        end
      else
        yield
      end
    end
  end
end

Version data entries

22 entries across 22 versions & 1 rubygems

Version Path
graphiti-1.0.beta.5 lib/graphiti/renderer.rb
graphiti-1.0.beta.4 lib/graphiti/renderer.rb
graphiti-1.0.beta.3 lib/graphiti/renderer.rb
graphiti-1.0.beta.2 lib/graphiti/renderer.rb
graphiti-1.0.alpha.26 lib/graphiti/renderer.rb
graphiti-1.0.alpha.25 lib/graphiti/renderer.rb
graphiti-1.0.alpha.24 lib/graphiti/renderer.rb
graphiti-1.0.alpha.23 lib/graphiti/renderer.rb
graphiti-1.0.alpha.22 lib/graphiti/renderer.rb
graphiti-1.0.alpha.21 lib/graphiti/renderer.rb
graphiti-1.0.alpha.20 lib/graphiti/renderer.rb
graphiti-1.0.alpha.19 lib/graphiti/renderer.rb
graphiti-1.0.alpha.18 lib/graphiti/renderer.rb
graphiti-1.0.alpha.17 lib/graphiti/renderer.rb
graphiti-1.0.alpha.16 lib/graphiti/renderer.rb
graphiti-1.0.alpha.15 lib/graphiti/renderer.rb
graphiti-1.0.alpha.14 lib/graphiti/renderer.rb
graphiti-1.0.alpha.12 lib/graphiti/renderer.rb
graphiti-1.0.alpha.11 lib/graphiti/renderer.rb
graphiti-1.0.alpha.10 lib/graphiti/renderer.rb