Module: Fakecrm::Drop

Included in:
Server
Defined in:
lib/fakecrm/drop.rb

Instance Method Summary collapse

Instance Method Details

#create_one(resource, data) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/fakecrm/drop.rb', line 4

def create_one(resource, data)
  response = {}
  resource.transaction do |t|
    instance = resource.new
    instance.attributes = data

    if instance.save
      response = ResourceView.decorate(instance)
    else
      status 422
      response = instance.errors.to_hash
    end
  end

  response.to_json
rescue ArgumentError => e
  status 422
  ::Fakecrm.logger.error("Unable to set unknown attribute: #{e.inspect}")
  {:error => "Unknown attribute #{e.inspect}"}.to_json 
end

#destroy_one(resource, primary_key) ⇒ Object



50
51
52
53
54
55
56
57
# File 'lib/fakecrm/drop.rb', line 50

def destroy_one(resource, primary_key)
  resource.transaction do |t|
    resource.get!(primary_key).destroy
  end
  body {}.to_json
rescue ::DataMapper::ObjectNotFoundError
  status 404
end

#update_one(resource, primary_key, data) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/fakecrm/drop.rb', line 25

def update_one(resource, primary_key, data)
  response = {}
  resource.transaction do |t|
    instance = resource.get!(primary_key)
    ::Fakecrm.logger.debug("Updating resource with: #{data.inspect}")
    instance.attributes = data

    if instance.save
      response = {}
    else
      status 422
      ::Fakecrm.logger.debug("Updating resouce failed: #{instance.errors.to_hash.inspect}")
      response = instance.errors.to_hash
    end
  end

  body response.to_json
rescue ::DataMapper::ObjectNotFoundError
  status 404
rescue ArgumentError => e
  status 422
  ::Fakecrm.logger.error("Unable to set unknown attribute: #{e.inspect}")
  {:error => "Unknown attribute #{e.inspect}"}.to_json 
end