Class: Roaster::Request

Inherits:
Object
  • Object
show all
Defined in:
lib/roaster/request.rb

Constant Summary collapse

ALLOWED_OPERATIONS =
[:create, :read, :update, :delete]

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(operation, target, resource, params, opts = {}) ⇒ Request

Returns a new instance of Request.



19
20
21
22
23
24
25
26
27
28
29
30
# 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

Class Method Details

.mapping_class_from_name(name) ⇒ Object



15
16
17
# 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) ⇒ Object

TODO: Move this elsewhere (factory)



7
8
9
10
11
12
13
# 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

Instance Method Details

#executeObject



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# 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).to_hash
  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