mender_paperclip 2.4.3

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 (70) hide show
  1. data/LICENSE +26 -0
  2. data/README.md +402 -0
  3. data/Rakefile +86 -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 +4 -0
  8. data/lib/generators/paperclip/USAGE +8 -0
  9. data/lib/generators/paperclip/paperclip_generator.rb +33 -0
  10. data/lib/generators/paperclip/templates/paperclip_migration.rb.erb +19 -0
  11. data/lib/paperclip/attachment.rb +454 -0
  12. data/lib/paperclip/callback_compatibility.rb +61 -0
  13. data/lib/paperclip/geometry.rb +120 -0
  14. data/lib/paperclip/interpolations.rb +181 -0
  15. data/lib/paperclip/iostream.rb +45 -0
  16. data/lib/paperclip/matchers/have_attached_file_matcher.rb +57 -0
  17. data/lib/paperclip/matchers/validate_attachment_content_type_matcher.rb +81 -0
  18. data/lib/paperclip/matchers/validate_attachment_presence_matcher.rb +54 -0
  19. data/lib/paperclip/matchers/validate_attachment_size_matcher.rb +95 -0
  20. data/lib/paperclip/matchers.rb +33 -0
  21. data/lib/paperclip/missing_attachment_styles.rb +87 -0
  22. data/lib/paperclip/options.rb +79 -0
  23. data/lib/paperclip/processor.rb +58 -0
  24. data/lib/paperclip/railtie.rb +26 -0
  25. data/lib/paperclip/storage/filesystem.rb +81 -0
  26. data/lib/paperclip/storage/fog.rb +162 -0
  27. data/lib/paperclip/storage/s3.rb +262 -0
  28. data/lib/paperclip/storage.rb +3 -0
  29. data/lib/paperclip/style.rb +95 -0
  30. data/lib/paperclip/thumbnail.rb +105 -0
  31. data/lib/paperclip/upfile.rb +62 -0
  32. data/lib/paperclip/version.rb +3 -0
  33. data/lib/paperclip.rb +478 -0
  34. data/lib/tasks/paperclip.rake +97 -0
  35. data/rails/init.rb +2 -0
  36. data/shoulda_macros/paperclip.rb +124 -0
  37. data/test/attachment_test.rb +1120 -0
  38. data/test/database.yml +4 -0
  39. data/test/fixtures/12k.png +0 -0
  40. data/test/fixtures/50x50.png +0 -0
  41. data/test/fixtures/5k.png +0 -0
  42. data/test/fixtures/animated.gif +0 -0
  43. data/test/fixtures/bad.png +1 -0
  44. data/test/fixtures/fog.yml +8 -0
  45. data/test/fixtures/s3.yml +8 -0
  46. data/test/fixtures/spaced file.png +0 -0
  47. data/test/fixtures/text.txt +1 -0
  48. data/test/fixtures/twopage.pdf +0 -0
  49. data/test/fixtures/uppercase.PNG +0 -0
  50. data/test/fog_test.rb +191 -0
  51. data/test/geometry_test.rb +206 -0
  52. data/test/helper.rb +152 -0
  53. data/test/integration_test.rb +654 -0
  54. data/test/interpolations_test.rb +195 -0
  55. data/test/iostream_test.rb +71 -0
  56. data/test/matchers/have_attached_file_matcher_test.rb +24 -0
  57. data/test/matchers/validate_attachment_content_type_matcher_test.rb +87 -0
  58. data/test/matchers/validate_attachment_presence_matcher_test.rb +26 -0
  59. data/test/matchers/validate_attachment_size_matcher_test.rb +51 -0
  60. data/test/options_test.rb +68 -0
  61. data/test/paperclip_missing_attachment_styles_test.rb +80 -0
  62. data/test/paperclip_test.rb +329 -0
  63. data/test/processor_test.rb +10 -0
  64. data/test/storage/filesystem_test.rb +52 -0
  65. data/test/storage/s3_live_test.rb +51 -0
  66. data/test/storage/s3_test.rb +633 -0
  67. data/test/style_test.rb +180 -0
  68. data/test/thumbnail_test.rb +383 -0
  69. data/test/upfile_test.rb +53 -0
  70. metadata +243 -0
data/lib/paperclip.rb ADDED
@@ -0,0 +1,478 @@
1
+ # Paperclip allows file attachments that are stored in the filesystem. All graphical
2
+ # transformations are done using the Graphics/ImageMagick command line utilities and
3
+ # are stored in Tempfiles until the record is saved. Paperclip does not require a
4
+ # separate model for storing the attachment's information, instead adding a few simple
5
+ # columns to your table.
6
+ #
7
+ # Author:: Jon Yurek
8
+ # Copyright:: Copyright (c) 2008-2011 thoughtbot, inc.
9
+ # License:: MIT License (http://www.opensource.org/licenses/mit-license.php)
10
+ #
11
+ # Paperclip defines an attachment as any file, though it makes special considerations
12
+ # for image files. You can declare that a model has an attached file with the
13
+ # +has_attached_file+ method:
14
+ #
15
+ # class User < ActiveRecord::Base
16
+ # has_attached_file :avatar, :styles => { :thumb => "100x100" }
17
+ # end
18
+ #
19
+ # user = User.new
20
+ # user.avatar = params[:user][:avatar]
21
+ # user.avatar.url
22
+ # # => "/users/avatars/4/original_me.jpg"
23
+ # user.avatar.url(:thumb)
24
+ # # => "/users/avatars/4/thumb_me.jpg"
25
+ #
26
+ # See the +has_attached_file+ documentation for more details.
27
+
28
+ require 'erb'
29
+ require 'digest'
30
+ require 'tempfile'
31
+ require 'paperclip/options'
32
+ require 'paperclip/version'
33
+ require 'paperclip/upfile'
34
+ require 'paperclip/iostream'
35
+ require 'paperclip/geometry'
36
+ require 'paperclip/processor'
37
+ require 'paperclip/thumbnail'
38
+ require 'paperclip/interpolations'
39
+ require 'paperclip/style'
40
+ require 'paperclip/attachment'
41
+ require 'paperclip/storage'
42
+ require 'paperclip/callback_compatibility'
43
+ require 'paperclip/missing_attachment_styles'
44
+ require 'paperclip/railtie'
45
+ require 'logger'
46
+ require 'cocaine'
47
+
48
+ # The base module that gets included in ActiveRecord::Base. See the
49
+ # documentation for Paperclip::ClassMethods for more useful information.
50
+ module Paperclip
51
+
52
+ class << self
53
+ # Provides configurability to Paperclip. There are a number of options available, such as:
54
+ # * whiny: Will raise an error if Paperclip cannot process thumbnails of
55
+ # an uploaded image. Defaults to true.
56
+ # * log: Logs progress to the Rails log. Uses ActiveRecord's logger, so honors
57
+ # log levels, etc. Defaults to true.
58
+ # * command_path: Defines the path at which to find the command line
59
+ # programs if they are not visible to Rails the system's search path. Defaults to
60
+ # nil, which uses the first executable found in the user's search path.
61
+ # * image_magick_path: Deprecated alias of command_path.
62
+ def options
63
+ @options ||= {
64
+ :whiny => true,
65
+ :image_magick_path => nil,
66
+ :command_path => nil,
67
+ :log => true,
68
+ :log_command => true,
69
+ :swallow_stderr => true
70
+ }
71
+ end
72
+
73
+ def configure
74
+ yield(self) if block_given?
75
+ end
76
+
77
+ def interpolates key, &block
78
+ Paperclip::Interpolations[key] = block
79
+ end
80
+
81
+ # The run method takes a command to execute and an array of parameters
82
+ # that get passed to it. The command is prefixed with the :command_path
83
+ # option from Paperclip.options. If you have many commands to run and
84
+ # they are in different paths, the suggested course of action is to
85
+ # symlink them so they are all in the same directory.
86
+ #
87
+ # If the command returns with a result code that is not one of the
88
+ # expected_outcodes, a Cocaine::CommandLineError will be raised. Generally
89
+ # a code of 0 is expected, but a list of codes may be passed if necessary.
90
+ # These codes should be passed as a hash as the last argument, like so:
91
+ #
92
+ # Paperclip.run("echo", "something", :expected_outcodes => [0,1,2,3])
93
+ #
94
+ # This method can log the command being run when
95
+ # Paperclip.options[:log_command] is set to true (defaults to false). This
96
+ # will only log if logging in general is set to true as well.
97
+ def run(cmd, *params)
98
+ if options[:image_magick_path]
99
+ Paperclip.log("[DEPRECATION] :image_magick_path is deprecated and will be removed. Use :command_path instead")
100
+ end
101
+ command_path = options[:command_path] || options[:image_magick_path]
102
+ Cocaine::CommandLine.path = ( Cocaine::CommandLine.path ? [Cocaine::CommandLine.path, command_path ].flatten : command_path )
103
+ Cocaine::CommandLine.logger = logger
104
+ Cocaine::CommandLine.new(cmd, *params).run
105
+ end
106
+
107
+ def processor(name) #:nodoc:
108
+ @known_processors ||= {}
109
+ if @known_processors[name.to_s]
110
+ @known_processors[name.to_s]
111
+ else
112
+ name = name.to_s.camelize
113
+ load_processor(name) unless Paperclip.const_defined?(name)
114
+ processor = Paperclip.const_get(name)
115
+ @known_processors[name.to_s] = processor
116
+ end
117
+ end
118
+
119
+ def load_processor(name)
120
+ if defined?(Rails.root) && Rails.root
121
+ require File.expand_path(Rails.root.join("lib", "paperclip_processors", "#{name.underscore}.rb"))
122
+ end
123
+ end
124
+
125
+ def clear_processors!
126
+ @known_processors.try(:clear)
127
+ end
128
+
129
+ # You can add your own processor via the Paperclip configuration. Normally
130
+ # Paperclip will load all processors from the
131
+ # Rails.root/lib/paperclip_processors directory, but here you can add any
132
+ # existing class using this mechanism.
133
+ #
134
+ # Paperclip.configure do |c|
135
+ # c.register_processor :watermarker, WatermarkingProcessor.new
136
+ # end
137
+ def register_processor(name, processor)
138
+ @known_processors ||= {}
139
+ @known_processors[name.to_s] = processor
140
+ end
141
+
142
+ # Find all instances of the given Active Record model +klass+ with attachment +name+.
143
+ # This method is used by the refresh rake tasks.
144
+ def each_instance_with_attachment(klass, name)
145
+ class_for(klass).find(:all, :order => 'id').each do |instance|
146
+ yield(instance) if instance.send(:"#{name}?")
147
+ end
148
+ end
149
+
150
+ # Log a paperclip-specific line. This will logs to STDOUT
151
+ # by default. Set Paperclip.options[:log] to false to turn off.
152
+ def log message
153
+ logger.info("[paperclip] #{message}") if logging?
154
+ end
155
+
156
+ def logger #:nodoc:
157
+ @logger ||= options[:logger] || Logger.new(STDOUT)
158
+ end
159
+
160
+ def logger=(logger)
161
+ @logger = logger
162
+ end
163
+
164
+ def logging? #:nodoc:
165
+ options[:log]
166
+ end
167
+
168
+ def class_for(class_name)
169
+ # Ruby 1.9 introduces an inherit argument for Module#const_get and
170
+ # #const_defined? and changes their default behavior.
171
+ # https://github.com/rails/rails/blob/v3.0.9/activesupport/lib/active_support/inflector/methods.rb#L89
172
+ if Module.method(:const_get).arity == 1
173
+ class_name.split('::').inject(Object) do |klass, partial_class_name|
174
+ klass.const_defined?(partial_class_name) ? klass.const_get(partial_class_name) : klass.const_missing(partial_class_name)
175
+ end
176
+ else
177
+ class_name.split('::').inject(Object) do |klass, partial_class_name|
178
+ klass.const_defined?(partial_class_name) ? klass.const_get(partial_class_name, false) : klass.const_missing(partial_class_name)
179
+ end
180
+ end
181
+ rescue ArgumentError => e
182
+ # Sadly, we need to capture ArguementError here because Rails 2.3.x
183
+ # Active Support dependency's management will try to the constant inherited
184
+ # from Object, and fail misably with "Object is not missing constant X" error
185
+ # https://github.com/rails/rails/blob/v2.3.12/activesupport/lib/active_support/dependencies.rb#L124
186
+ if e.message =~ /is not missing constant/
187
+ raise NameError, "uninitialized constant #{class_name}"
188
+ else
189
+ raise e
190
+ end
191
+ end
192
+
193
+ def check_for_url_clash(name,url,klass)
194
+ @names_url ||= {}
195
+ default_url = url || Attachment.default_options[:url]
196
+ if @names_url[name] && @names_url[name][:url] == default_url && @names_url[name][:class] != klass
197
+ log("Duplicate URL for #{name} with #{default_url}. This will clash with attachment defined in #{@names_url[name][:class]} class")
198
+ end
199
+ @names_url[name] = {:url => default_url, :class => klass}
200
+ end
201
+
202
+ def reset_duplicate_clash_check!
203
+ @names_url = nil
204
+ end
205
+ end
206
+
207
+ class PaperclipError < StandardError #:nodoc:
208
+ end
209
+
210
+ class StorageMethodNotFound < PaperclipError
211
+ end
212
+
213
+ class CommandNotFoundError < PaperclipError
214
+ end
215
+
216
+ class NotIdentifiedByImageMagickError < PaperclipError #:nodoc:
217
+ end
218
+
219
+ class InfiniteInterpolationError < PaperclipError #:nodoc:
220
+ end
221
+
222
+ module Glue
223
+ def self.included base #:nodoc:
224
+ base.extend ClassMethods
225
+ base.class_attribute :attachment_definitions if base.respond_to?(:class_attribute)
226
+ if base.respond_to?(:set_callback)
227
+ base.send :include, Paperclip::CallbackCompatability::Rails3
228
+ else
229
+ base.send :include, Paperclip::CallbackCompatability::Rails21
230
+ end
231
+ end
232
+ end
233
+
234
+ module ClassMethods
235
+ # +has_attached_file+ gives the class it is called on an attribute that maps to a file. This
236
+ # is typically a file stored somewhere on the filesystem and has been uploaded by a user.
237
+ # The attribute returns a Paperclip::Attachment object which handles the management of
238
+ # that file. The intent is to make the attachment as much like a normal attribute. The
239
+ # thumbnails will be created when the new file is assigned, but they will *not* be saved
240
+ # until +save+ is called on the record. Likewise, if the attribute is set to +nil+ is
241
+ # called on it, the attachment will *not* be deleted until +save+ is called. See the
242
+ # Paperclip::Attachment documentation for more specifics. There are a number of options
243
+ # you can set to change the behavior of a Paperclip attachment:
244
+ # * +url+: The full URL of where the attachment is publically accessible. This can just
245
+ # as easily point to a directory served directly through Apache as it can to an action
246
+ # that can control permissions. You can specify the full domain and path, but usually
247
+ # just an absolute path is sufficient. The leading slash *must* be included manually for
248
+ # absolute paths. The default value is
249
+ # "/system/:attachment/:id/:style/:filename". See
250
+ # Paperclip::Attachment#interpolate for more information on variable interpolaton.
251
+ # :url => "/:class/:attachment/:id/:style_:filename"
252
+ # :url => "http://some.other.host/stuff/:class/:id_:extension"
253
+ # * +default_url+: The URL that will be returned if there is no attachment assigned.
254
+ # This field is interpolated just as the url is. The default value is
255
+ # "/:attachment/:style/missing.png"
256
+ # has_attached_file :avatar, :default_url => "/images/default_:style_avatar.png"
257
+ # User.new.avatar_url(:small) # => "/images/default_small_avatar.png"
258
+ # * +styles+: A hash of thumbnail styles and their geometries. You can find more about
259
+ # geometry strings at the ImageMagick website
260
+ # (http://www.imagemagick.org/script/command-line-options.php#resize). Paperclip
261
+ # also adds the "#" option (e.g. "50x50#"), which will resize the image to fit maximally
262
+ # inside the dimensions and then crop the rest off (weighted at the center). The
263
+ # default value is to generate no thumbnails.
264
+ # * +default_style+: The thumbnail style that will be used by default URLs.
265
+ # Defaults to +original+.
266
+ # has_attached_file :avatar, :styles => { :normal => "100x100#" },
267
+ # :default_style => :normal
268
+ # user.avatar.url # => "/avatars/23/normal_me.png"
269
+ # * +whiny+: Will raise an error if Paperclip cannot post_process an uploaded file due
270
+ # to a command line error. This will override the global setting for this attachment.
271
+ # Defaults to true. This option used to be called :whiny_thumbanils, but this is
272
+ # deprecated.
273
+ # * +convert_options+: When creating thumbnails, use this free-form options
274
+ # array to pass in various convert command options. Typical options are "-strip" to
275
+ # remove all Exif data from the image (save space for thumbnails and avatars) or
276
+ # "-depth 8" to specify the bit depth of the resulting conversion. See ImageMagick
277
+ # convert documentation for more options: (http://www.imagemagick.org/script/convert.php)
278
+ # Note that this option takes a hash of options, each of which correspond to the style
279
+ # of thumbnail being generated. You can also specify :all as a key, which will apply
280
+ # to all of the thumbnails being generated. If you specify options for the :original,
281
+ # it would be best if you did not specify destructive options, as the intent of keeping
282
+ # the original around is to regenerate all the thumbnails when requirements change.
283
+ # has_attached_file :avatar, :styles => { :large => "300x300", :negative => "100x100" }
284
+ # :convert_options => {
285
+ # :all => "-strip",
286
+ # :negative => "-negate"
287
+ # }
288
+ # NOTE: While not deprecated yet, it is not recommended to specify options this way.
289
+ # It is recommended that :convert_options option be included in the hash passed to each
290
+ # :styles for compatibility with future versions.
291
+ # NOTE: Strings supplied to :convert_options are split on space in order to undergo
292
+ # shell quoting for safety. If your options require a space, please pre-split them
293
+ # and pass an array to :convert_options instead.
294
+ # * +storage+: Chooses the storage backend where the files will be stored. The current
295
+ # choices are :filesystem and :s3. The default is :filesystem. Make sure you read the
296
+ # documentation for Paperclip::Storage::Filesystem and Paperclip::Storage::S3
297
+ # for backend-specific options.
298
+ #
299
+ # It's also possible for you to dynamicly define your interpolation string for :url,
300
+ # :default_url, and :path in your model by passing a method name as a symbol as a argument
301
+ # for your has_attached_file definition:
302
+ #
303
+ # class Person
304
+ # has_attached_file :avatar, :default_url => :default_url_by_gender
305
+ #
306
+ # private
307
+ #
308
+ # def default_url_by_gender
309
+ # "/assets/avatars/default_#{gender}.png"
310
+ # end
311
+ # end
312
+ def has_attached_file name, options = {}
313
+ include InstanceMethods
314
+
315
+ if attachment_definitions.nil?
316
+ if respond_to?(:class_attribute)
317
+ self.attachment_definitions = {}
318
+ else
319
+ write_inheritable_attribute(:attachment_definitions, {})
320
+ end
321
+ end
322
+
323
+ attachment_definitions[name] = {:validations => []}.merge(options)
324
+ Paperclip.classes_with_attachments << self.name
325
+ Paperclip.check_for_url_clash(name,attachment_definitions[name][:url],self.name)
326
+
327
+ after_save :save_attached_files
328
+ before_destroy :prepare_for_destroy
329
+ after_destroy :destroy_attached_files
330
+
331
+ define_paperclip_callbacks :post_process, :"#{name}_post_process"
332
+
333
+ define_method name do |*args|
334
+ a = attachment_for(name)
335
+ (args.length > 0) ? a.to_s(args.first) : a
336
+ end
337
+
338
+ define_method "#{name}=" do |file|
339
+ attachment_for(name).assign(file)
340
+ end
341
+
342
+ define_method "#{name}?" do
343
+ attachment_for(name).file?
344
+ end
345
+
346
+ validates_each(name) do |record, attr, value|
347
+ attachment = record.attachment_for(name)
348
+ attachment.send(:flush_errors)
349
+ end
350
+ end
351
+
352
+ # Places ActiveRecord-style validations on the size of the file assigned. The
353
+ # possible options are:
354
+ # * +in+: a Range of bytes (i.e. +1..1.megabyte+),
355
+ # * +less_than+: equivalent to :in => 0..options[:less_than]
356
+ # * +greater_than+: equivalent to :in => options[:greater_than]..Infinity
357
+ # * +message+: error message to display, use :min and :max as replacements
358
+ # * +if+: A lambda or name of a method on the instance. Validation will only
359
+ # be run is this lambda or method returns true.
360
+ # * +unless+: Same as +if+ but validates if lambda or method returns false.
361
+ def validates_attachment_size name, options = {}
362
+ min = options[:greater_than] || (options[:in] && options[:in].first) || 0
363
+ max = options[:less_than] || (options[:in] && options[:in].last) || (1.0/0)
364
+ range = (min..max)
365
+ message = options[:message] || "file size must be between :min and :max bytes"
366
+ message = message.call if message.respond_to?(:call)
367
+ message = message.gsub(/:min/, min.to_s).gsub(/:max/, max.to_s)
368
+
369
+ validates_inclusion_of :"#{name}_file_size",
370
+ :in => range,
371
+ :message => message,
372
+ :if => options[:if],
373
+ :unless => options[:unless],
374
+ :allow_nil => true
375
+ end
376
+
377
+ # Adds errors if thumbnail creation fails. The same as specifying :whiny_thumbnails => true.
378
+ def validates_attachment_thumbnails name, options = {}
379
+ warn('[DEPRECATION] validates_attachment_thumbnail is deprecated. ' +
380
+ 'This validation is on by default and will be removed from future versions. ' +
381
+ 'If you wish to turn it off, supply :whiny => false in your definition.')
382
+ attachment_definitions[name][:whiny_thumbnails] = true
383
+ end
384
+
385
+ # Places ActiveRecord-style validations on the presence of a file.
386
+ # Options:
387
+ # * +if+: A lambda or name of a method on the instance. Validation will only
388
+ # be run is this lambda or method returns true.
389
+ # * +unless+: Same as +if+ but validates if lambda or method returns false.
390
+ def validates_attachment_presence name, options = {}
391
+ message = options[:message] || :empty
392
+ validates_presence_of :"#{name}_file_name",
393
+ :message => message,
394
+ :if => options[:if],
395
+ :unless => options[:unless]
396
+ end
397
+
398
+ # Places ActiveRecord-style validations on the content type of the file
399
+ # assigned. The possible options are:
400
+ # * +content_type+: Allowed content types. Can be a single content type
401
+ # or an array. Each type can be a String or a Regexp. It should be
402
+ # noted that Internet Explorer upload files with content_types that you
403
+ # may not expect. For example, JPEG images are given image/pjpeg and
404
+ # PNGs are image/x-png, so keep that in mind when determining how you
405
+ # match. Allows all by default.
406
+ # * +message+: The message to display when the uploaded file has an invalid
407
+ # content type.
408
+ # * +if+: A lambda or name of a method on the instance. Validation will only
409
+ # be run is this lambda or method returns true.
410
+ # * +unless+: Same as +if+ but validates if lambda or method returns false.
411
+ # NOTE: If you do not specify an [attachment]_content_type field on your
412
+ # model, content_type validation will work _ONLY upon assignment_ and
413
+ # re-validation after the instance has been reloaded will always succeed.
414
+ # You'll still need to have a virtual attribute (created by +attr_accessor+)
415
+ # name +[attachment]_content_type+ to be able to use this validator.
416
+ def validates_attachment_content_type name, options = {}
417
+ validation_options = options.dup
418
+ allowed_types = [validation_options[:content_type]].flatten
419
+ validates_each(:"#{name}_content_type", validation_options) do |record, attr, value|
420
+ if !allowed_types.any?{|t| t === value } && !(value.nil? || value.blank?)
421
+ if record.errors.method(:add).arity == -2
422
+ message = options[:message] || "is not one of #{allowed_types.join(", ")}"
423
+ message = message.call if message.respond_to?(:call)
424
+ record.errors.add(:"#{name}_content_type", message)
425
+ else
426
+ record.errors.add(:"#{name}_content_type", :inclusion, :default => options[:message], :value => value)
427
+ end
428
+ end
429
+ end
430
+ end
431
+
432
+ # Returns the attachment definitions defined by each call to
433
+ # has_attached_file.
434
+ def attachment_definitions
435
+ if respond_to?(:class_attribute)
436
+ self.attachment_definitions
437
+ else
438
+ read_inheritable_attribute(:attachment_definitions)
439
+ end
440
+ end
441
+ end
442
+
443
+ module InstanceMethods #:nodoc:
444
+ def attachment_for name
445
+ @_paperclip_attachments ||= {}
446
+ @_paperclip_attachments[name] ||= Attachment.new(name, self, self.class.attachment_definitions[name])
447
+ end
448
+
449
+ def each_attachment
450
+ self.class.attachment_definitions.each do |name, definition|
451
+ yield(name, attachment_for(name))
452
+ end
453
+ end
454
+
455
+ def save_attached_files
456
+ Paperclip.log("Saving attachments.")
457
+ each_attachment do |name, attachment|
458
+ attachment.send(:save)
459
+ end
460
+ end
461
+
462
+ def destroy_attached_files
463
+ Paperclip.log("Deleting attachments.")
464
+ each_attachment do |name, attachment|
465
+ attachment.send(:flush_deletes)
466
+ end
467
+ end
468
+
469
+ def prepare_for_destroy
470
+ Paperclip.log("Scheduling attachments for deletion.")
471
+ each_attachment do |name, attachment|
472
+ attachment.send(:queue_existing_for_delete)
473
+ end
474
+ end
475
+
476
+ end
477
+
478
+ end
@@ -0,0 +1,97 @@
1
+ module Paperclip
2
+ module Task
3
+ def self.obtain_class
4
+ class_name = ENV['CLASS'] || ENV['class']
5
+ raise "Must specify CLASS" unless class_name
6
+ class_name
7
+ end
8
+
9
+ def self.obtain_attachments(klass)
10
+ klass = Paperclip.class_for(klass.to_s)
11
+ name = ENV['ATTACHMENT'] || ENV['attachment']
12
+ raise "Class #{klass.name} has no attachments specified" unless klass.respond_to?(:attachment_definitions)
13
+ if !name.blank? && klass.attachment_definitions.keys.include?(name)
14
+ [ name ]
15
+ else
16
+ klass.attachment_definitions.keys
17
+ end
18
+ end
19
+ end
20
+ end
21
+
22
+ namespace :paperclip do
23
+ desc "Refreshes both metadata and thumbnails."
24
+ task :refresh => ["paperclip:refresh:metadata", "paperclip:refresh:thumbnails"]
25
+
26
+ namespace :refresh do
27
+ desc "Regenerates thumbnails for a given CLASS (and optional ATTACHMENT and STYLES splitted by comma)."
28
+ task :thumbnails => :environment do
29
+ errors = []
30
+ klass = Paperclip::Task.obtain_class
31
+ names = Paperclip::Task.obtain_attachments(klass)
32
+ styles = (ENV['STYLES'] || ENV['styles'] || '').split(',').map(&:to_sym)
33
+ names.each do |name|
34
+ Paperclip.each_instance_with_attachment(klass, name) do |instance|
35
+ instance.send(name).reprocess!(*styles)
36
+ errors << [instance.id, instance.errors] unless instance.errors.blank?
37
+ end
38
+ end
39
+ errors.each{|e| puts "#{e.first}: #{e.last.full_messages.inspect}" }
40
+ end
41
+
42
+ desc "Regenerates content_type/size metadata for a given CLASS (and optional ATTACHMENT)."
43
+ task :metadata => :environment do
44
+ klass = Paperclip::Task.obtain_class
45
+ names = Paperclip::Task.obtain_attachments(klass)
46
+ names.each do |name|
47
+ Paperclip.each_instance_with_attachment(klass, name) do |instance|
48
+ if file = instance.send(name).to_file(:original)
49
+ instance.send("#{name}_file_name=", instance.send("#{name}_file_name").strip)
50
+ instance.send("#{name}_content_type=", file.content_type.strip)
51
+ instance.send("#{name}_file_size=", file.size) if instance.respond_to?("#{name}_file_size")
52
+ if Rails.version >= "3.0.0"
53
+ instance.save(:validate => false)
54
+ else
55
+ instance.save(false)
56
+ end
57
+ else
58
+ true
59
+ end
60
+ end
61
+ end
62
+ end
63
+
64
+ desc "Regenerates missing thumbnail styles for all classes using Paperclip."
65
+ task :missing_styles => :environment do
66
+ # Force loading all model classes to never miss any has_attached_file declaration:
67
+ Dir[Rails.root + 'app/models/**/*.rb'].each { |path| load path }
68
+ Paperclip.missing_attachments_styles.each do |klass, attachment_definitions|
69
+ attachment_definitions.each do |attachment_name, missing_styles|
70
+ puts "Regenerating #{klass} -> #{attachment_name} -> #{missing_styles.inspect}"
71
+ ENV['CLASS'] = klass.to_s
72
+ ENV['ATTACHMENT'] = attachment_name.to_s
73
+ ENV['STYLES'] = missing_styles.join(',')
74
+ Rake::Task['paperclip:refresh:thumbnails'].execute
75
+ end
76
+ end
77
+ Paperclip.save_current_attachments_styles!
78
+ end
79
+ end
80
+
81
+ desc "Cleans out invalid attachments. Useful after you've added new validations."
82
+ task :clean => :environment do
83
+ klass = Paperclip::Task.obtain_class
84
+ names = Paperclip::Task.obtain_attachments(klass)
85
+ names.each do |name|
86
+ Paperclip.each_instance_with_attachment(klass, name) do |instance|
87
+ instance.send(name).send(:validate)
88
+ if instance.send(name).valid?
89
+ true
90
+ else
91
+ instance.send("#{name}=", nil)
92
+ instance.save
93
+ end
94
+ end
95
+ end
96
+ end
97
+ end
data/rails/init.rb ADDED
@@ -0,0 +1,2 @@
1
+ require 'paperclip/railtie'
2
+ Paperclip::Railtie.insert