/
instance_methods.rb
54 lines (48 loc) · 1.4 KB
/
instance_methods.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
module Joint
module InstanceMethods
def grid
@grid ||= Mongo::Grid.new(database)
end
private
def assigned_attachments
@assigned_attachments ||= {}
end
def nil_attachments
@nil_attachments ||= Set.new
end
# IO must respond to read and rewind
def save_attachments
assigned_attachments.each_pair do |name, io|
next unless io.respond_to?(:read)
io.rewind if io.respond_to?(:rewind)
grid.delete(send(name).id)
grid.put(io, {
:_id => send(name).id,
:filename => send(name).name,
:content_type => send(name).type,
})
end
assigned_attachments.clear
end
def destroy_nil_attachments
# currently MM does not send sets to instance as well
nil_attachments.each do |name|
grid.delete(send(name).id)
send(:"#{name}_id=", nil)
send(:"#{name}_size=", nil)
send(:"#{name}_type=", nil)
send(:"#{name}_name=", nil)
set({
:"#{name}_id" => nil,
:"#{name}_size" => nil,
:"#{name}_type" => nil,
:"#{name}_name" => nil,
})
end
nil_attachments.clear
end
def destroy_all_attachments
self.class.attachment_names.map { |name| grid.delete(send(name).id) }
end
end
end