path-paperclip 2.3.3

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