class Shaf::Responder::Hal

Public Class Methods

can_handle?(resource) click to toggle source
# File lib/shaf/responder/hal.rb, line 7
def self.can_handle?(resource)
  return false if resource.is_a? StandardError

  if resource.is_a? Class
    return false if resource <= Shaf::Profile
  end

  true
end

Public Instance Methods

body() click to toggle source
# File lib/shaf/responder/hal.rb, line 17
def body
  @body ||= generate_json
end
lookup_rel(rel, response) click to toggle source
# File lib/shaf/responder/hal.rb, line 21
def lookup_rel(rel, response)
  hal = response.serialized_hash
  links = hal&.dig(:_links, rel.to_sym)
  return [] unless links

  links = [links] unless links.is_a? Array
  links.map do |link|
    {
      href: link[:href],
      as: 'fetch',
      crossorigin: 'anonymous'
    }
  end
end

Private Instance Methods

collection?() click to toggle source
# File lib/shaf/responder/hal.rb, line 43
def collection?
  !!options.fetch(:collection, false)
end
generate_json() click to toggle source
# File lib/shaf/responder/hal.rb, line 79
def generate_json
  # FIXME: change to Oj??
  JSON.generate(serialized_hash)
end
mime_type() click to toggle source
Calls superclass method Shaf::Responder::Base::mime_type
# File lib/shaf/responder/hal.rb, line 37
def mime_type
  type = super
  type = "#{type}; profile=\"#{profile}\"" if profile
  type
end
profile() click to toggle source
# File lib/shaf/responder/hal.rb, line 72
def profile
  @profile ||= options[:profile]
  return unless @profile || serializer

  @profile ||= serializer.semantic_profile
end
serialized_hash() click to toggle source
# File lib/shaf/responder/hal.rb, line 51
def serialized_hash
  raise Errors::NotAcceptableError unless serializer

  @serialized_hash ||=
    if collection?
      serializer.to_collection(resource, current_user: user, as_hash: true, **options)
    else
      serializer.to_hal(resource, current_user: user, as_hash: true, **options)
    end

  # hal_presenter versions before v1.5.0 does not understand the :as_hash
  # keyword argument and will always return a String from
  # to_hal/to_collection, thus we need to parse it if its a String.
  if @serialized_hash.is_a? String
    @body = @serialized_hash
    @serialized_hash = JSON.parse(@serialized_hash, symbolize_names: true)
  end

  @serialized_hash
end
serializer() click to toggle source
# File lib/shaf/responder/hal.rb, line 47
def serializer
  @serializer ||= options[:serializer] || HALPresenter.lookup_presenter(resource)
end