-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontact_presenter.rb
71 lines (62 loc) · 1.74 KB
/
contact_presenter.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
require 'rails/resource_service'
require_relative '../models/contact'
class ContactPresenter
attr_accessor :contacts, :edit_index
def initialize(attributes_of_contacts)
@contacts = attributes_of_contacts.map do |attributes_of_contact|
Contact.new(attributes_of_contact.transform_keys(&:to_sym))
end
end
def form_contact
time_in_millis = Time.now.to_i
@form_contact ||= Contact.new
end
def save_contact
if form_contact.id.nil?
add_contact
else
update_contact
end
end
def add_contact
Rails::ResourceService.create(resource: form_contact) do |response, created_contact, errors|
if response.ok?
contacts << created_contact
form_contact.reset
form_contact.errors = nil
else
form_contact.errors = errors
end
end
end
def update_contact
Rails::ResourceService.update(resource: form_contact) do |response, updated_contact, errors|
if response.ok?
contacts[edit_index].load_with(updated_contact)
self.edit_index = nil
form_contact.reset
form_contact.errors = nil
else
form_contact.errors = errors
end
end
end
def edit_contact(contact)
self.edit_index = contacts.index(contact)
form_contact.load_with(contact)
form_contact.errors = nil
end
def delete_contact(contact)
delete_contact_confirmation = $$.confirm("Are you sure you want to delete that contact?")
if delete_contact_confirmation
Rails::ResourceService.destroy(resource: contact) do |response|
if response.ok?
contacts.delete(contact)
self.edit_index = nil
form_contact.reset
form_contact.errors = nil
end
end
end
end
end