106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
|
# File 'lib/attach/model_extension.rb', line 106
def attachment(name, options = {}, &block)
unless self.reflect_on_all_associations(:has_many).map(&:name).include?(:attachments)
has_many :attachments, :as => :owner, :dependent => :destroy, :class_name => 'Attach::Attachment'
end
dsl = AttachmentDSL.new(&block)
dsl.processors.each do |processor|
Processor.register(self, name, &processor)
end
if dsl.validators.size > 0
validate do
attachment = @pending_attachments && @pending_attachments[name] ? @pending_attachments[name] : send(name)
file_errors = []
dsl.validators.each do |validator|
validator.call(attachment, file_errors)
end
file_errors.each { |e| errors.add("#{name}_file", e) }
end
end
define_method name do
var = instance_variable_get("@#{name}")
if var
var == :nil ? nil : var
else
if attachment = self.attachments.where(:role => name, :parent_id => nil).first
instance_variable_set("@#{name}", attachment)
else
instance_variable_set("@#{name}", :nil)
nil
end
end
end
define_method "#{name}=" do |file|
if file.is_a?(Attach::Attachment)
attachment = file
elsif file
attachment = Attachment.new({:owner => self, :role => name}.merge(options))
case file
when ActionDispatch::Http::UploadedFile
attachment.binary = file.tempfile.read
attachment.file_name = file.original_filename
attachment.file_type = file.content_type
when Attach::File
attachment.binary = file.data
attachment.file_name = file.name
attachment.file_type = file.type
else
attachment.binary = file
attachment.file_name = "untitled"
attachment.file_type = "application/octet-stream"
end
end
if attachment
@pending_attachments ||= {}
@pending_attachments[name] = attachment
end
instance_variable_set("@#{name}", attachment)
end
define_method "#{name}_delete" do
instance_variable_get("@#{name}_delete")
end
define_method "#{name}_delete=" do |delete|
delete = delete.to_i
instance_variable_set("@#{name}_delete", delete)
if delete == 1
@pending_attachment_deletions ||= []
@pending_attachment_deletions << name
end
end
end
|