bteitelb-paperclip 2.3.1.1

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