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
|
# File 'lib/saviour/integrator.rb', line 8
def setup!
raise(ConfigurationError, "You cannot include Saviour::Model twice in the same class") if @klass.respond_to?(:attached_files)
@klass.class_attribute :attached_files
@klass.attached_files = []
@klass.class_attribute :attached_followers_per_leader
@klass.attached_followers_per_leader = {}
klass = @klass
persistence_klass = @persistence_klass
@klass.define_singleton_method "attach_file" do |attach_as, *maybe_uploader_klass, **opts, &block|
klass.attached_files.push(attach_as)
uploader_klass = maybe_uploader_klass[0]
if opts[:follow]
klass.attached_followers_per_leader[opts[:follow]] ||= []
klass.attached_followers_per_leader[opts[:follow]].push(attach_as)
end
if uploader_klass.nil? && block.nil?
raise ConfigurationError, "you must provide either an UploaderClass or a block to define it."
end
mod = Module.new do
define_method(attach_as) do
instance_variable_get("@__uploader_#{attach_as}") || begin
uploader_klass = Class.new(Saviour::BaseUploader, &block) if block
new_file = ::Saviour::File.new(uploader_klass, self, attach_as)
layer = persistence_klass.new(self)
new_file.set_path!(layer.read(attach_as))
instance_variable_set("@__uploader_#{attach_as}", new_file)
end
end
define_method("#{attach_as}=") do |value|
send(attach_as).assign(value)
end
define_method("#{attach_as}_changed?") do
send(attach_as).changed?
end
define_method("remove_#{attach_as}!") do
work = proc do
send(attach_as).delete
layer = persistence_klass.new(self)
layer.write(attach_as, nil)
end
if ActiveRecord::Base.connection.current_transaction.open?
DbHelpers.run_after_commit &work
else
work.call
end
end
end
klass.include mod
end
@klass.class_attribute :__saviour_validations
@klass.define_singleton_method("attach_validation") do |attach_as, method_name = nil, &block|
klass.__saviour_validations ||= Hash.new { [] }
klass.__saviour_validations[attach_as] += [{ method_or_block: method_name || block, type: :memory }]
end
@klass.define_singleton_method("attach_validation_with_file") do |attach_as, method_name = nil, &block|
klass.__saviour_validations ||= Hash.new { [] }
klass.__saviour_validations[attach_as] += [{ method_or_block: method_name || block, type: :file }]
end
end
|