module Garage::HypermediaResponder

Public Instance Methods

display(resource, given_options={}) click to toggle source
Calls superclass method
# File lib/garage/hypermedia_responder.rb, line 5
def display(resource, given_options={})
  given_options[:content_type] = representation.content_type if representation.dictionary?
  super(render(transform(resource)), given_options)
end
encode_to_hash(resource, *args) click to toggle source

Cache resource encoding result if the resource can be identified. Garage try to get resource identifier by acccess the resource `#resource_identifier` or `#id`.

# File lib/garage/hypermedia_responder.rb, line 25
def encode_to_hash(resource, *args)
  if id = get_resource_identifier(resource)
    options = args[0] || {}
    selector = options[:selector] || controller.field_selector
    cache_key = "#{resource.class.name}:#{id}:#{selector.canonical}"
    cache[cache_key] ||= _encode_to_hash(resource, *args)
  else
    _encode_to_hash(resource, *args)
  end
end
render(data) click to toggle source
# File lib/garage/hypermedia_responder.rb, line 10
def render(data)
  DataRenderer.render(data, dictionary: representation.dictionary?)
end
transform(resources) click to toggle source
# File lib/garage/hypermedia_responder.rb, line 14
def transform(resources)
  if resources.respond_to?(:map) && resources.respond_to?(:to_a)
    resources.map {|resource| encode_to_hash(resource, partial: true) }
  else
    encode_to_hash(resources)
  end
end

Private Instance Methods

_encode_to_hash(resource, options = {}) click to toggle source
# File lib/garage/hypermedia_responder.rb, line 38
def _encode_to_hash(resource, options = {})
  resource.represent!
  resource.params = controller.params.slice(*resource.class.params)
  resource.partial = options[:partial]
  resource.selector = options[:selector] || controller.field_selector
  resource.render_hash(:responder => self)
end
cache() click to toggle source
# File lib/garage/hypermedia_responder.rb, line 46
def cache
  @cache ||= {}
end
get_resource_identifier(resource) click to toggle source
# File lib/garage/hypermedia_responder.rb, line 50
def get_resource_identifier(resource)
  case
  when resource.respond_to?(:resource_identifier)
    resource.resource_identifier
  when resource.respond_to?(:id)
    resource.id
  else
    nil
  end
end
representation() click to toggle source
# File lib/garage/hypermedia_responder.rb, line 61
def representation
  @representation ||= Representation.new(controller)
end