class Roaster::Request

Constants

ALLOWED_OPERATIONS

Public Class Methods

mapping_class_from_name(name) click to toggle source
# File lib/roaster/request.rb, line 15
def self.mapping_class_from_name(name)
  "#{name.to_s.singularize}_mapping".classify.constantize
end
mapping_class_from_target(target) click to toggle source

TODO: Move this elsewhere (factory)

# File lib/roaster/request.rb, line 7
def self.mapping_class_from_target(target)
  if target.relationship_name
    mapping_class_from_name(target.relationship_name)
  else
    mapping_class_from_name(target.resource_name)
  end
end
new(operation, target, resource, params, opts = {}) click to toggle source
# File lib/roaster/request.rb, line 19
def initialize(operation, target, resource, params, opts = {})
  # :create, :read, :update, :delete
  unless ALLOWED_OPERATIONS.include?(operation)
    raise "#{operation} is not a valid operation."
  end
  @operation = operation
  @resource = resource
  @mapping_class = opts[:mapping_class] || self.class.mapping_class_from_target(target)
  @query = Roaster::Query.new(@operation, target, @mapping_class, params)
  #TODO: Oh snap this is confusing
  @document = opts[:document]
end

Public Instance Methods

execute() click to toggle source
# File lib/roaster/request.rb, line 32
def execute
  case @operation
  when :create
    #TODO: - IDEA - Maybe make `new` return a fake 'relationship' object so a relationship special case wouldn't be needed
    if @query.target.relationship_name.nil?
      obj = @resource.new(@query)
      parse(obj, @document)
      @resource.save(obj)
    else
      @resource.create_relationship(@query, @document)
    end
  when :read
    res = @resource.query(@query)
    represent(res)
  when :update
    obj = @resource.find(@query)
    links = @document.delete('links')
    @resource.update_relationships(@query, links) if links
    parse(obj, @document)
    @resource.save(obj)
  when :delete
    @resource.delete(@query)
  end
end

Private Instance Methods

parse(object, data) click to toggle source
# File lib/roaster/request.rb, line 59
def parse(object, data)
  rp = @mapping_class.new(object)
  rp.from_hash(data)
end
represent(data) click to toggle source
# File lib/roaster/request.rb, line 64
def represent(data)
  if @query.target.resource_ids.size == 1
    @mapping_class.prepare(data.first).to_hash({roaster: :resource})
  elsif data.respond_to?(:each)
    @mapping_class.for_collection.prepare(data).to_hash({roaster: :collection}, Roaster::JsonApi::CollectionBinding)
  else
    # TODO: HANDLE ERROR ?
    byebug
  end
end