forked from zammad/zammad
-
Notifications
You must be signed in to change notification settings - Fork 0
/
upload_cache.rb
98 lines (88 loc) · 2.13 KB
/
upload_cache.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
# A wrapper class around Store that handles temporary attachment uploads
# and provides an interface for those.
class UploadCache
attr_reader :id
# Initializes a UploadCache for a given form_id.
#
# @example
# cache = UploadCache.new(form_id)
#
# @return [UploadCache]
def initialize(id)
# conversion to Integer is required for proper Store#o_id comparsion
@id = id.to_i
end
# Adds a Store item with the given attributes for the form_id.
#
# @see Store#add
#
# @example
# cache = UploadCache.new(form_id)
# store = cache.add(
# filename: file.original_filename,
# data: file.read,
# preferences: {
# 'Content-Type' => 'application/octet-stream'
# }
# )
#
# @return [Store] the created Store item
def add(args)
Store.add(
args.merge(
object: store_object,
o_id: id,
)
)
end
# Provides all Store items associated to the form_id.
#
# @see Store#list
#
# @example
# attachments = UploadCache.new(form_id).attachments
#
# @return [Array<Store>] an enumerator of Store items
def attachments
Store.list(
object: store_object,
o_id: id,
)
end
# Removes all Store items associated to the form_id.
#
# @see Store#remove
#
# @example
# UploadCache.new(form_id).destroy
#
def destroy
Store.remove(
object: store_object,
o_id: id,
)
end
# Removes all Store items associated to the form_id.
#
# @see Store#remove
#
# @example
# UploadCache.new(form_id).remove_item(store_id)
#
# @raise [Exceptions::UnprocessableEntity] in cases where a Store item should get deleted that is not an UploadCache item
#
def remove_item(store_id = nil)
store = Store.find(store_id)
if store.o_id != id || store.store_object_id != store_object_id
raise Exceptions::UnprocessableEntity, "Attempt to delete Store item #{store_id} that is not bound to UploadCache object"
end
Store.remove_item(store_id)
end
private
def store_object
self.class.name
end
def store_object_id
Store::Object.lookup(name: store_object).id
end
end