area17-paperclip 2.2.9.1.1

Sign up to get free protection for your applications and to get access to all the features.
Files changed (47) hide show
  1. data/LICENSE +26 -0
  2. data/README.rdoc +174 -0
  3. data/Rakefile +99 -0
  4. data/generators/paperclip/USAGE +5 -0
  5. data/generators/paperclip/paperclip_generator.rb +27 -0
  6. data/generators/paperclip/templates/paperclip_migration.rb.erb +19 -0
  7. data/init.rb +1 -0
  8. data/lib/paperclip.rb +350 -0
  9. data/lib/paperclip/attachment.rb +464 -0
  10. data/lib/paperclip/callback_compatability.rb +33 -0
  11. data/lib/paperclip/geometry.rb +150 -0
  12. data/lib/paperclip/interpolations.rb +105 -0
  13. data/lib/paperclip/iostream.rb +58 -0
  14. data/lib/paperclip/matchers.rb +4 -0
  15. data/lib/paperclip/matchers/have_attached_file_matcher.rb +49 -0
  16. data/lib/paperclip/matchers/validate_attachment_content_type_matcher.rb +66 -0
  17. data/lib/paperclip/matchers/validate_attachment_presence_matcher.rb +48 -0
  18. data/lib/paperclip/matchers/validate_attachment_size_matcher.rb +83 -0
  19. data/lib/paperclip/processor.rb +49 -0
  20. data/lib/paperclip/storage.rb +238 -0
  21. data/lib/paperclip/thumbnail.rb +70 -0
  22. data/lib/paperclip/upfile.rb +44 -0
  23. data/shoulda_macros/paperclip.rb +68 -0
  24. data/tasks/paperclip_tasks.rake +97 -0
  25. data/test/attachment_test.rb +774 -0
  26. data/test/database.yml +4 -0
  27. data/test/fixtures/12k.png +0 -0
  28. data/test/fixtures/50x50.png +0 -0
  29. data/test/fixtures/5k.png +0 -0
  30. data/test/fixtures/bad.png +1 -0
  31. data/test/fixtures/s3.yml +4 -0
  32. data/test/fixtures/text.txt +0 -0
  33. data/test/fixtures/twopage.pdf +0 -0
  34. data/test/geometry_test.rb +177 -0
  35. data/test/helper.rb +100 -0
  36. data/test/integration_test.rb +481 -0
  37. data/test/interpolations_test.rb +120 -0
  38. data/test/iostream_test.rb +71 -0
  39. data/test/matchers/have_attached_file_matcher_test.rb +21 -0
  40. data/test/matchers/validate_attachment_content_type_matcher_test.rb +30 -0
  41. data/test/matchers/validate_attachment_presence_matcher_test.rb +21 -0
  42. data/test/matchers/validate_attachment_size_matcher_test.rb +50 -0
  43. data/test/paperclip_test.rb +291 -0
  44. data/test/processor_test.rb +10 -0
  45. data/test/storage_test.rb +278 -0
  46. data/test/thumbnail_test.rb +177 -0
  47. metadata +124 -0
@@ -0,0 +1,464 @@
1
+ module Paperclip
2
+ # The Attachment class manages the files for a given attachment. It saves
3
+ # when the model saves, deletes when the model is destroyed, and processes
4
+ # the file upon assignment.
5
+ class Attachment
6
+
7
+ def self.default_options
8
+ @default_options ||= {
9
+ :url => "/system/:attachment/:id/:style/:filename",
10
+ :path => ":rails_root/public:url",
11
+ :styles => {},
12
+ :default_url => "/:attachment/:style/missing.png",
13
+ :default_style => :original,
14
+ :validations => [],
15
+ :storage => :filesystem,
16
+ :whiny => Paperclip.options[:whiny] || Paperclip.options[:whiny_thumbnails]
17
+ }
18
+ end
19
+
20
+ attr_reader :name, :instance, :styles, :default_style, :convert_options, :queued_for_write, :options
21
+
22
+ # Creates an Attachment object. +name+ is the name of the attachment,
23
+ # +instance+ is the ActiveRecord object instance it's attached to, and
24
+ # +options+ is the same as the hash passed to +has_attached_file+.
25
+ def initialize name, instance, options = {}
26
+ @name = name
27
+ @instance = instance
28
+
29
+ options = self.class.default_options.merge(options)
30
+
31
+ @url = options[:url]
32
+ @url = @url.call(self) if @url.is_a?(Proc)
33
+ @path = options[:path]
34
+ @path = @path.call(self) if @path.is_a?(Proc)
35
+ @styles = options[:styles]
36
+ @styles = @styles.call(self) if @styles.is_a?(Proc)
37
+ @default_url = options[:default_url]
38
+ @validations = options[:validations]
39
+ @default_style = options[:default_style]
40
+ @storage = options[:storage]
41
+ @whiny = options[:whiny_thumbnails] || options[:whiny]
42
+ @convert_options = options[:convert_options] || {}
43
+ @processors = options[:processors] || [:thumbnail]
44
+ @options = options
45
+ @queued_for_delete = []
46
+ @queued_for_write = {}
47
+ @errors = {}
48
+ @dimensions = {}
49
+ @validation_errors = nil
50
+ @dirty = false
51
+
52
+ normalize_style_definition
53
+ initialize_storage
54
+ end
55
+
56
+ # What gets called when you call instance.attachment = File. It clears
57
+ # errors, assigns attributes, processes the file, and runs validations. It
58
+ # also queues up the previous file for deletion, to be flushed away on
59
+ # #save of its host. In addition to form uploads, you can also assign
60
+ # another Paperclip attachment:
61
+ # new_user.avatar = old_user.avatar
62
+ # If the file that is assigned is not valid, the processing (i.e.
63
+ # thumbnailing, etc) will NOT be run.
64
+ def assign uploaded_file
65
+ ensure_required_accessors!
66
+
67
+ if uploaded_file.is_a?(Paperclip::Attachment)
68
+ uploaded_file = uploaded_file.to_file(:original)
69
+ close_uploaded_file = uploaded_file.respond_to?(:close)
70
+ end
71
+
72
+ return nil unless valid_assignment?(uploaded_file)
73
+
74
+ uploaded_file.binmode if uploaded_file.respond_to? :binmode
75
+ self.clear
76
+
77
+ return nil if uploaded_file.nil?
78
+
79
+ @queued_for_write[:original] = uploaded_file.to_tempfile
80
+ instance_write(:file_name, uploaded_file.original_filename.strip.gsub(/[^\w\d\.\-]+/, '_'))
81
+ instance_write(:content_type, uploaded_file.content_type.to_s.strip)
82
+ instance_write(:file_size, uploaded_file.size.to_i)
83
+ instance_write(:updated_at, Time.now)
84
+
85
+ @dirty = true
86
+
87
+ post_process if valid?
88
+
89
+ # Reset the file size if the original file was reprocessed.
90
+ instance_write(:file_size, @queued_for_write[:original].size.to_i)
91
+
92
+ if image? and
93
+ @instance.class.column_names.include?("#{name}_width") and
94
+ @instance.class.column_names.include?("#{name}_height")
95
+
96
+ begin
97
+ geometry = Paperclip::Geometry.from_file(@queued_for_write[:original])
98
+ instance_write(:width, geometry.width.to_i)
99
+ instance_write(:height, geometry.height.to_i)
100
+ rescue NotIdentifiedByImageMagickError => e
101
+ log("Couldn't get dimensions for #{name}: #{e}")
102
+ end
103
+ else
104
+ instance_write(:width, nil)
105
+ instance_write(:height, nil)
106
+ end
107
+ ensure
108
+ uploaded_file.close if close_uploaded_file
109
+ validate
110
+ end
111
+
112
+ # Returns the public URL of the attachment, with a given style. Note that
113
+ # this does not necessarily need to point to a file that your web server
114
+ # can access and can point to an action in your app, if you need fine
115
+ # grained security. This is not recommended if you don't need the
116
+ # security, however, for performance reasons. set
117
+ # include_updated_timestamp to false if you want to stop the attachment
118
+ # update time appended to the url
119
+ def url style = default_style, include_updated_timestamp = true
120
+ url = original_filename.nil? ? interpolate(@default_url, style) : interpolate(@url, style)
121
+ include_updated_timestamp && updated_at ? [url, updated_at].compact.join(url.include?("?") ? "&" : "?") : url
122
+ end
123
+
124
+ # Returns the path of the attachment as defined by the :path option. If the
125
+ # file is stored in the filesystem the path refers to the path of the file
126
+ # on disk. If the file is stored in S3, the path is the "key" part of the
127
+ # URL, and the :bucket option refers to the S3 bucket.
128
+ def path style = default_style
129
+ original_filename.nil? ? nil : interpolate(@path, style)
130
+ end
131
+
132
+ # Alias to +url+
133
+ def to_s style = nil
134
+ url(style)
135
+ end
136
+
137
+ # Returns true if there are no errors on this attachment.
138
+ def valid?
139
+ validate
140
+ errors.empty?
141
+ end
142
+
143
+ # Returns an array containing the errors on this attachment.
144
+ def errors
145
+ @errors
146
+ end
147
+
148
+ # Returns true if there are changes that need to be saved.
149
+ def dirty?
150
+ @dirty
151
+ end
152
+
153
+ # Saves the file, if there are no errors. If there are, it flushes them to
154
+ # the instance's errors and returns false, cancelling the save.
155
+ def save
156
+ if valid?
157
+ flush_deletes
158
+ flush_writes
159
+ @dirty = false
160
+ true
161
+ else
162
+ flush_errors
163
+ false
164
+ end
165
+ end
166
+
167
+ # Clears out the attachment. Has the same effect as previously assigning
168
+ # nil to the attachment. Does NOT save. If you wish to clear AND save,
169
+ # use #destroy.
170
+ def clear
171
+ queue_existing_for_delete
172
+ @errors = {}
173
+ @validation_errors = nil
174
+ end
175
+
176
+ # Destroys the attachment. Has the same effect as previously assigning
177
+ # nil to the attachment *and saving*. This is permanent. If you wish to
178
+ # wipe out the existing attachment but not save, use #clear.
179
+ def destroy
180
+ clear
181
+ save
182
+ end
183
+
184
+ # Returns the name of the file as originally assigned, and lives in the
185
+ # <attachment>_file_name attribute of the model.
186
+ def original_filename
187
+ instance_read(:file_name)
188
+ end
189
+
190
+ # Returns the size of the file as originally assigned, and lives in the
191
+ # <attachment>_file_size attribute of the model.
192
+ def size
193
+ instance_read(:file_size) || (@queued_for_write[:original] && @queued_for_write[:original].size)
194
+ end
195
+
196
+ # Returns the content_type of the file as originally assigned, and lives
197
+ # in the <attachment>_content_type attribute of the model.
198
+ def content_type
199
+ instance_read(:content_type)
200
+ end
201
+
202
+ # Returns the last modified time of the file as originally assigned, and
203
+ # lives in the <attachment>_updated_at attribute of the model.
204
+ def updated_at
205
+ time = instance_read(:updated_at)
206
+ time && time.to_i
207
+ end
208
+
209
+ # If <attachment> is an image and <attachment>_width attribute is present, returns the original width
210
+ # of the image when no argument is specified or the calculated new width of the image when passed a
211
+ # valid style. Returns nil otherwise
212
+ def width style = default_style
213
+ dimensions(style)[0]
214
+ end
215
+
216
+ # If <attachment> is an image and <attachment>_height attribute is present, returns the original width
217
+ # of the image when no argument is specified or the calculated new height of the image when passed a
218
+ # valid style. Returns nil otherwise
219
+ def height style = default_style
220
+ dimensions(style)[1]
221
+ end
222
+
223
+ # Paths and URLs can have a number of variables interpolated into them
224
+ # to vary the storage location based on name, id, style, class, etc.
225
+ # This method is a deprecated access into supplying and retrieving these
226
+ # interpolations. Future access should use either Paperclip.interpolates
227
+ # or extend the Paperclip::Interpolations module directly.
228
+ def self.interpolations
229
+ warn('[DEPRECATION] Paperclip::Attachment.interpolations is deprecated ' +
230
+ 'and will be removed from future versions. ' +
231
+ 'Use Paperclip.interpolates instead')
232
+ Paperclip::Interpolations
233
+ end
234
+
235
+ # This method really shouldn't be called that often. It's expected use is
236
+ # in the paperclip:refresh rake task and that's it. It will regenerate all
237
+ # thumbnails forcefully, by reobtaining the original file and going through
238
+ # the post-process again.
239
+ def reprocess!
240
+ new_original = Tempfile.new("paperclip-reprocess")
241
+ new_original.binmode
242
+ if old_original = to_file(:original)
243
+ new_original.write( old_original.read )
244
+ new_original.rewind
245
+
246
+ @queued_for_write = { :original => new_original }
247
+ post_process
248
+
249
+ old_original.close if old_original.respond_to?(:close)
250
+
251
+ save
252
+ else
253
+ true
254
+ end
255
+ end
256
+
257
+ # Returns true if a file has been assigned.
258
+ def file?
259
+ !original_filename.blank?
260
+ end
261
+
262
+ # Determines whether or not the attachment is an image based on the content_type
263
+ def image?
264
+ !content_type.nil? and !!content_type.match(%r{\Aimage/})
265
+ end
266
+
267
+ # Writes the attachment-specific attribute on the instance. For example,
268
+ # instance_write(:file_name, "me.jpg") will write "me.jpg" to the instance's
269
+ # "avatar_file_name" field (assuming the attachment is called avatar).
270
+ def instance_write(attr, value)
271
+ setter = :"#{name}_#{attr}="
272
+ responds = instance.respond_to?(setter)
273
+ self.instance_variable_set("@_#{setter.to_s.chop}", value)
274
+ instance.send(setter, value) if responds || attr.to_s == "file_name"
275
+ end
276
+
277
+ # Reads the attachment-specific attribute on the instance. See instance_write
278
+ # for more details.
279
+ def instance_read(attr)
280
+ getter = :"#{name}_#{attr}"
281
+ responds = instance.respond_to?(getter)
282
+ cached = self.instance_variable_get("@_#{getter}")
283
+ return cached if cached
284
+ instance.send(getter) if responds || attr.to_s == "file_name"
285
+ end
286
+
287
+ private
288
+
289
+ def ensure_required_accessors! #:nodoc:
290
+ %w(file_name).each do |field|
291
+ unless @instance.respond_to?("#{name}_#{field}") && @instance.respond_to?("#{name}_#{field}=")
292
+ raise PaperclipError.new("#{@instance.class} model missing required attr_accessor for '#{name}_#{field}'")
293
+ end
294
+ end
295
+ end
296
+
297
+ def log message #:nodoc:
298
+ Paperclip.log(message)
299
+ end
300
+
301
+ def valid_assignment? file #:nodoc:
302
+ file.nil? || (file.respond_to?(:original_filename) && file.respond_to?(:content_type))
303
+ end
304
+
305
+ def validate #:nodoc:
306
+ unless @validation_errors
307
+ @validation_errors = @validations.inject({}) do |errors, validation|
308
+ name, options = validation
309
+ errors[name] = send(:"validate_#{name}", options) if allow_validation?(options)
310
+ errors
311
+ end
312
+ @validation_errors.reject!{|k,v| v == nil }
313
+ @errors.merge!(@validation_errors)
314
+ end
315
+ @validation_errors
316
+ end
317
+
318
+ def allow_validation? options #:nodoc:
319
+ (options[:if].nil? || check_guard(options[:if])) && (options[:unless].nil? || !check_guard(options[:unless]))
320
+ end
321
+
322
+ def check_guard guard #:nodoc:
323
+ if guard.respond_to? :call
324
+ guard.call(instance)
325
+ elsif ! guard.blank?
326
+ instance.send(guard.to_s)
327
+ end
328
+ end
329
+
330
+ def validate_size options #:nodoc:
331
+ if file? && !options[:range].include?(size.to_i)
332
+ options[:message].gsub(/:min/, options[:min].to_s).gsub(/:max/, options[:max].to_s)
333
+ end
334
+ end
335
+
336
+ def validate_presence options #:nodoc:
337
+ options[:message] unless file?
338
+ end
339
+
340
+ def validate_content_type options #:nodoc:
341
+ valid_types = [options[:content_type]].flatten
342
+ unless original_filename.blank?
343
+ unless valid_types.blank?
344
+ content_type = instance_read(:content_type)
345
+ unless valid_types.any?{|t| content_type.nil? || t === content_type }
346
+ options[:message] || "is not one of the allowed file types."
347
+ end
348
+ end
349
+ end
350
+ end
351
+
352
+ def normalize_style_definition #:nodoc:
353
+ @styles.each do |name, args|
354
+ unless args.is_a? Hash
355
+ dimensions, format = [args, nil].flatten[0..1]
356
+ format = nil if format.blank?
357
+ @styles[name] = {
358
+ :processors => @processors,
359
+ :geometry => dimensions,
360
+ :format => format,
361
+ :whiny => @whiny,
362
+ :convert_options => extra_options_for(name)
363
+ }
364
+ else
365
+ @styles[name] = {
366
+ :processors => @processors,
367
+ :whiny => @whiny,
368
+ :convert_options => extra_options_for(name)
369
+ }.merge(@styles[name])
370
+ end
371
+ end
372
+ end
373
+
374
+ def solidify_style_definitions #:nodoc:
375
+ @styles.each do |name, args|
376
+ @styles[name][:geometry] = @styles[name][:geometry].call(instance) if @styles[name][:geometry].respond_to?(:call)
377
+ @styles[name][:processors] = @styles[name][:processors].call(instance) if @styles[name][:processors].respond_to?(:call)
378
+ end
379
+ end
380
+
381
+ def initialize_storage #:nodoc:
382
+ @storage_module = Paperclip::Storage.const_get(@storage.to_s.capitalize)
383
+ self.extend(@storage_module)
384
+ end
385
+
386
+ def extra_options_for(style) #:nodoc:
387
+ all_options = convert_options[:all]
388
+ all_options = all_options.call(instance) if all_options.respond_to?(:call)
389
+ style_options = convert_options[style]
390
+ style_options = style_options.call(instance) if style_options.respond_to?(:call)
391
+
392
+ [ style_options, all_options ].compact.join(" ")
393
+ end
394
+
395
+ def post_process #:nodoc:
396
+ return if @queued_for_write[:original].nil?
397
+ solidify_style_definitions
398
+ return if fire_events(:before)
399
+ post_process_styles
400
+ return if fire_events(:after)
401
+ end
402
+
403
+ def fire_events(which) #:nodoc:
404
+ return true if callback(:"#{which}_post_process") == false
405
+ return true if callback(:"#{which}_#{name}_post_process") == false
406
+ end
407
+
408
+ def callback which #:nodoc:
409
+ instance.run_callbacks(which, @queued_for_write){|result, obj| result == false }
410
+ end
411
+
412
+ def post_process_styles #:nodoc:
413
+ @styles.each do |name, args|
414
+ begin
415
+ raise RuntimeError.new("Style #{name} has no processors defined.") if args[:processors].blank?
416
+ @queued_for_write[name] = args[:processors].inject(@queued_for_write[:original]) do |file, processor|
417
+ Paperclip.processor(processor).make(file, args, self)
418
+ end
419
+ rescue PaperclipError => e
420
+ log("An error was received while processing: #{e.inspect}")
421
+ (@errors[:processing] ||= []) << e.message if @whiny
422
+ end
423
+ end
424
+ end
425
+
426
+ def interpolate pattern, style = default_style #:nodoc:
427
+ Paperclip::Interpolations.interpolate(pattern, self, style)
428
+ end
429
+
430
+ def dimensions style = default_style
431
+ return [nil,nil] unless image?
432
+ return @dimensions[style] unless @dimensions[style].nil?
433
+ w, h = instance_read(:width), instance_read(:height)
434
+
435
+ if @styles[style].nil? or @styles[style][:geometry].nil?
436
+ @dimensions[style] = [w,h]
437
+ else
438
+ @dimensions[style] = Geometry.parse(@styles[style][:geometry]).new_dimensions_for(w, h)
439
+ end
440
+ end
441
+
442
+ def queue_existing_for_delete #:nodoc:
443
+ return unless file?
444
+ @queued_for_delete += [:original, *@styles.keys].uniq.map do |style|
445
+ path(style) if exists?(style)
446
+ end.compact
447
+ instance_write(:file_name, nil)
448
+ instance_write(:content_type, nil)
449
+ instance_write(:file_size, nil)
450
+ instance_write(:updated_at, nil)
451
+ instance_write(:width, nil)
452
+ instance_write(:height, nil)
453
+ @dimensions = {}
454
+ end
455
+
456
+ def flush_errors #:nodoc:
457
+ @errors.each do |error, message|
458
+ [message].flatten.each {|m| instance.errors.add(name, m) }
459
+ end
460
+ end
461
+
462
+ end
463
+ end
464
+