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
|
# File 'lib/image_thread/model_methods.rb', line 9
def has_image_thread(field, opt = {})
field_id = [field, 'id'].join('_')
before_save_method = ['append_images', field].join('_')
delete = opt[:delete] || []
class_eval do
belongs_to field, class_name: 'ImageThread::Thread'
before_save before_save_method.to_sym
define_method before_save_method do
thread_id = nil
images = instance_variable_get(:"@#{field}_images")
return if images.blank?
image_ids = instance_variable_get(:"@#{field}_images").map { |i| i[:id] }
ImageThread::Image.select('id, thread_id').where(id: image_ids).each do |image|
if !thread_id.blank? && thread_id != image.thread_id
raise DifferentThreads, "Try to save images from different thread as one. Image ids: #{image_ids}"
end
thread_id = image.thread_id
end
transaction do
instance_variable_get(:"@#{field}_images").each do |image|
img = ImageThread::Image.find image[:id]
unless img.blank?
if image[:state] == 'default'
img.thread.update_attribute(:default_image_id, img.id)
next
end
img.update(state: image[:state]) unless image[:state].blank?
if img.state == ImageThread::Image::STATE_DELETED
if delete.include?(:files)
dir_name = File.dirname(img.source.path)
file_name = File.basename(img.source.path)
Dir.chdir(dir_name)
Dir.glob(['*', file_name].join).each do |file|
File.delete File.expand_path(file)
end
File.expand_path img.source
end
img.destroy if delete.include?(:row) || delete.include?(:files)
end
end
end
end
_assign_attribute(field_id, thread_id)
instance_variable_set(:"@#{field}_images", [])
end
define_method [field, '_', 'images','='].join do |images|
res = []
images.each do |image|
id, state = image.split(':')
res << {id: id, state: state}
end
instance_variable_set(:"@#{field}_images", res)
end
define_method [field, 'images'].join('_') do
instance_variable_get(:"@#{field}_images")
end
end
end
|