class Praxis::Renderer

Attributes

cache[R]
include_nil[R]

Public Class Methods

new(include_nil: false) click to toggle source
# File lib/praxis/renderer.rb, line 21
def initialize(include_nil: false)
  @cache = Hash.new do |hash, key|
    hash[key] = {}
  end

  @include_nil = include_nil
end

Public Instance Methods

_render(object, fields, context: Attributor::DEFAULT_ROOT_CONTEXT) click to toggle source
# File lib/praxis/renderer.rb, line 48
def _render(object, fields, context: Attributor::DEFAULT_ROOT_CONTEXT)
  if fields == true
    return case object
           when Attributor::Dumpable
             object.dump
           else
             object
           end
  end

  fields.each_with_object({}) do |(key, subfields), hash|
    begin
      value = object._get_attr(key)
    rescue StandardError => e
      raise Attributor::DumpError.new(context: context, name: key, type: object.class, original_exception: e)
    end

    if value.nil?
      hash[key] = nil if include_nil
      next
    end

    if subfields == true
      hash[key] = case value
                  when Attributor::Dumpable
                    value.dump
                  else
                    value
                  end
    else
      new_context = context + [key]
      hash[key] = render(value, subfields, context: new_context)
    end
  end
end
render(object, fields, context: Attributor::DEFAULT_ROOT_CONTEXT) click to toggle source

Renders an object using a given list of fields.

@param [Object] object the object to render @param [Hash] fields the correct set of fields, as from FieldExpander

# File lib/praxis/renderer.rb, line 33
def render(object, fields, context: Attributor::DEFAULT_ROOT_CONTEXT)
  if object.is_a? Praxis::Blueprint
    @cache[object._cache_key][fields] ||= _render(object, fields, context: context)
  elsif object.class < Attributor::Collection
    object.each_with_index.collect do |sub_object, i|
      sub_context = context + ["at(#{i})"]
      render(sub_object, fields, context: sub_context)
    end
  else
    _render(object, fields, context: context)
  end
rescue SystemStackError
  raise CircularRenderingError.new(object, context)
end