ryansch-paperclip 2.3.10

Sign up to get free protection for your applications and to get access to all the features.
Files changed (63) hide show
  1. data/LICENSE +26 -0
  2. data/README.md +239 -0
  3. data/Rakefile +80 -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 +384 -0
  12. data/lib/paperclip/attachment.rb +378 -0
  13. data/lib/paperclip/callback_compatability.rb +61 -0
  14. data/lib/paperclip/command_line.rb +86 -0
  15. data/lib/paperclip/geometry.rb +115 -0
  16. data/lib/paperclip/interpolations.rb +130 -0
  17. data/lib/paperclip/iostream.rb +45 -0
  18. data/lib/paperclip/matchers.rb +33 -0
  19. data/lib/paperclip/matchers/have_attached_file_matcher.rb +57 -0
  20. data/lib/paperclip/matchers/validate_attachment_content_type_matcher.rb +75 -0
  21. data/lib/paperclip/matchers/validate_attachment_presence_matcher.rb +54 -0
  22. data/lib/paperclip/matchers/validate_attachment_size_matcher.rb +95 -0
  23. data/lib/paperclip/processor.rb +58 -0
  24. data/lib/paperclip/railtie.rb +24 -0
  25. data/lib/paperclip/storage.rb +3 -0
  26. data/lib/paperclip/storage/filesystem.rb +74 -0
  27. data/lib/paperclip/storage/fog.rb +98 -0
  28. data/lib/paperclip/storage/s3.rb +192 -0
  29. data/lib/paperclip/style.rb +91 -0
  30. data/lib/paperclip/thumbnail.rb +79 -0
  31. data/lib/paperclip/upfile.rb +55 -0
  32. data/lib/paperclip/version.rb +3 -0
  33. data/lib/tasks/paperclip.rake +72 -0
  34. data/rails/init.rb +2 -0
  35. data/shoulda_macros/paperclip.rb +118 -0
  36. data/test/attachment_test.rb +939 -0
  37. data/test/command_line_test.rb +138 -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/bad.png +1 -0
  43. data/test/fixtures/s3.yml +8 -0
  44. data/test/fixtures/text.txt +0 -0
  45. data/test/fixtures/twopage.pdf +0 -0
  46. data/test/fixtures/uppercase.PNG +0 -0
  47. data/test/fog_test.rb +107 -0
  48. data/test/geometry_test.rb +177 -0
  49. data/test/helper.rb +146 -0
  50. data/test/integration_test.rb +570 -0
  51. data/test/interpolations_test.rb +143 -0
  52. data/test/iostream_test.rb +71 -0
  53. data/test/matchers/have_attached_file_matcher_test.rb +24 -0
  54. data/test/matchers/validate_attachment_content_type_matcher_test.rb +47 -0
  55. data/test/matchers/validate_attachment_presence_matcher_test.rb +26 -0
  56. data/test/matchers/validate_attachment_size_matcher_test.rb +51 -0
  57. data/test/paperclip_test.rb +306 -0
  58. data/test/processor_test.rb +10 -0
  59. data/test/storage_test.rb +416 -0
  60. data/test/style_test.rb +163 -0
  61. data/test/thumbnail_test.rb +227 -0
  62. data/test/upfile_test.rb +36 -0
  63. metadata +233 -0
@@ -0,0 +1,19 @@
1
+ class <%= migration_class_name %> < ActiveRecord::Migration
2
+ def self.up
3
+ <% attachment_names.each do |attachment| -%>
4
+ add_column :<%= name.underscore.camelize.tableize %>, :<%= attachment %>_file_name, :string
5
+ add_column :<%= name.underscore.camelize.tableize %>, :<%= attachment %>_content_type, :string
6
+ add_column :<%= name.underscore.camelize.tableize %>, :<%= attachment %>_file_size, :integer
7
+ add_column :<%= name.underscore.camelize.tableize %>, :<%= attachment %>_updated_at, :datetime
8
+ <% end -%>
9
+ end
10
+
11
+ def self.down
12
+ <% attachment_names.each do |attachment| -%>
13
+ remove_column :<%= name.underscore.camelize.tableize %>, :<%= attachment %>_file_name
14
+ remove_column :<%= name.underscore.camelize.tableize %>, :<%= attachment %>_content_type
15
+ remove_column :<%= name.underscore.camelize.tableize %>, :<%= attachment %>_file_size
16
+ remove_column :<%= name.underscore.camelize.tableize %>, :<%= attachment %>_updated_at
17
+ <% end -%>
18
+ end
19
+ end
data/lib/paperclip.rb ADDED
@@ -0,0 +1,384 @@
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-2009 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/version'
32
+ require 'paperclip/upfile'
33
+ require 'paperclip/iostream'
34
+ require 'paperclip/geometry'
35
+ require 'paperclip/processor'
36
+ require 'paperclip/thumbnail'
37
+ require 'paperclip/interpolations'
38
+ require 'paperclip/style'
39
+ require 'paperclip/attachment'
40
+ require 'paperclip/storage'
41
+ require 'paperclip/callback_compatability'
42
+ require 'paperclip/command_line'
43
+ require 'paperclip/railtie'
44
+ if defined?(Rails.root) && Rails.root
45
+ Dir.glob(File.join(File.expand_path(Rails.root), "lib", "paperclip_processors", "*.rb")).each do |processor|
46
+ require processor
47
+ end
48
+ end
49
+
50
+ # The base module that gets included in ActiveRecord::Base. See the
51
+ # documentation for Paperclip::ClassMethods for more useful information.
52
+ module Paperclip
53
+
54
+ class << self
55
+ # Provides configurability to Paperclip. There are a number of options available, such as:
56
+ # * whiny: Will raise an error if Paperclip cannot process thumbnails of
57
+ # an uploaded image. Defaults to true.
58
+ # * log: Logs progress to the Rails log. Uses ActiveRecord's logger, so honors
59
+ # log levels, etc. Defaults to true.
60
+ # * command_path: Defines the path at which to find the command line
61
+ # programs if they are not visible to Rails the system's search path. Defaults to
62
+ # nil, which uses the first executable found in the user's search path.
63
+ # * image_magick_path: Deprecated alias of command_path.
64
+ def options
65
+ @options ||= {
66
+ :whiny => true,
67
+ :image_magick_path => nil,
68
+ :command_path => nil,
69
+ :log => true,
70
+ :log_command => true,
71
+ :swallow_stderr => true
72
+ }
73
+ end
74
+
75
+ def configure
76
+ yield(self) if block_given?
77
+ end
78
+
79
+ def interpolates key, &block
80
+ Paperclip::Interpolations[key] = block
81
+ end
82
+
83
+ # The run method takes a command to execute and an array of parameters
84
+ # that get passed to it. The command is prefixed with the :command_path
85
+ # option from Paperclip.options. If you have many commands to run and
86
+ # they are in different paths, the suggested course of action is to
87
+ # symlink them so they are all in the same directory.
88
+ #
89
+ # If the command returns with a result code that is not one of the
90
+ # expected_outcodes, a PaperclipCommandLineError will be raised. Generally
91
+ # a code of 0 is expected, but a list of codes may be passed if necessary.
92
+ # These codes should be passed as a hash as the last argument, like so:
93
+ #
94
+ # Paperclip.run("echo", "something", :expected_outcodes => [0,1,2,3])
95
+ #
96
+ # This method can log the command being run when
97
+ # Paperclip.options[:log_command] is set to true (defaults to false). This
98
+ # will only log if logging in general is set to true as well.
99
+ def run cmd, *params
100
+ if options[:image_magick_path]
101
+ Paperclip.log("[DEPRECATION] :image_magick_path is deprecated and will be removed. Use :command_path instead")
102
+ end
103
+ CommandLine.path = options[:command_path] || options[:image_magick_path]
104
+ CommandLine.new(cmd, *params).run
105
+ end
106
+
107
+ def processor name #:nodoc:
108
+ name = name.to_s.camelize
109
+ processor = Paperclip.const_get(name)
110
+ unless processor.ancestors.include?(Paperclip::Processor)
111
+ raise PaperclipError.new("Processor #{name} was not found")
112
+ end
113
+ processor
114
+ end
115
+
116
+ def each_instance_with_attachment(klass, name)
117
+ class_for(klass).all.each do |instance|
118
+ yield(instance) if instance.send(:"#{name}?")
119
+ end
120
+ end
121
+
122
+ # Log a paperclip-specific line. Uses ActiveRecord::Base.logger
123
+ # by default. Set Paperclip.options[:log] to false to turn off.
124
+ def log message
125
+ logger.info("[paperclip] #{message}") if logging?
126
+ end
127
+
128
+ def logger #:nodoc:
129
+ ActiveRecord::Base.logger
130
+ end
131
+
132
+ def logging? #:nodoc:
133
+ options[:log]
134
+ end
135
+
136
+ def class_for(class_name)
137
+ class_name.split('::').inject(Object) do |klass, partial_class_name|
138
+ klass.const_get(partial_class_name)
139
+ end
140
+ end
141
+ end
142
+
143
+ class PaperclipError < StandardError #:nodoc:
144
+ end
145
+
146
+ class PaperclipCommandLineError < PaperclipError #:nodoc:
147
+ attr_accessor :output
148
+ def initialize(msg = nil, output = nil)
149
+ super(msg)
150
+ @output = output
151
+ end
152
+ end
153
+
154
+ class StorageMethodNotFound < PaperclipError
155
+ end
156
+
157
+ class CommandNotFoundError < PaperclipError
158
+ end
159
+
160
+ class NotIdentifiedByImageMagickError < PaperclipError #:nodoc:
161
+ end
162
+
163
+ class InfiniteInterpolationError < PaperclipError #:nodoc:
164
+ end
165
+
166
+ module Glue
167
+ def self.included base #:nodoc:
168
+ base.extend ClassMethods
169
+ if base.respond_to?("set_callback")
170
+ base.send :include, Paperclip::CallbackCompatability::Rails3
171
+ else
172
+ base.send :include, Paperclip::CallbackCompatability::Rails21
173
+ end
174
+ end
175
+ end
176
+
177
+ module ClassMethods
178
+ # +has_attached_file+ gives the class it is called on an attribute that maps to a file. This
179
+ # is typically a file stored somewhere on the filesystem and has been uploaded by a user.
180
+ # The attribute returns a Paperclip::Attachment object which handles the management of
181
+ # that file. The intent is to make the attachment as much like a normal attribute. The
182
+ # thumbnails will be created when the new file is assigned, but they will *not* be saved
183
+ # until +save+ is called on the record. Likewise, if the attribute is set to +nil+ is
184
+ # called on it, the attachment will *not* be deleted until +save+ is called. See the
185
+ # Paperclip::Attachment documentation for more specifics. There are a number of options
186
+ # you can set to change the behavior of a Paperclip attachment:
187
+ # * +url+: The full URL of where the attachment is publically accessible. This can just
188
+ # as easily point to a directory served directly through Apache as it can to an action
189
+ # that can control permissions. You can specify the full domain and path, but usually
190
+ # just an absolute path is sufficient. The leading slash *must* be included manually for
191
+ # absolute paths. The default value is
192
+ # "/system/:attachment/:id/:style/:filename". See
193
+ # Paperclip::Attachment#interpolate for more information on variable interpolaton.
194
+ # :url => "/:class/:attachment/:id/:style_:filename"
195
+ # :url => "http://some.other.host/stuff/:class/:id_:extension"
196
+ # * +default_url+: The URL that will be returned if there is no attachment assigned.
197
+ # This field is interpolated just as the url is. The default value is
198
+ # "/:attachment/:style/missing.png"
199
+ # has_attached_file :avatar, :default_url => "/images/default_:style_avatar.png"
200
+ # User.new.avatar_url(:small) # => "/images/default_small_avatar.png"
201
+ # * +styles+: A hash of thumbnail styles and their geometries. You can find more about
202
+ # geometry strings at the ImageMagick website
203
+ # (http://www.imagemagick.org/script/command-line-options.php#resize). Paperclip
204
+ # also adds the "#" option (e.g. "50x50#"), which will resize the image to fit maximally
205
+ # inside the dimensions and then crop the rest off (weighted at the center). The
206
+ # default value is to generate no thumbnails.
207
+ # * +default_style+: The thumbnail style that will be used by default URLs.
208
+ # Defaults to +original+.
209
+ # has_attached_file :avatar, :styles => { :normal => "100x100#" },
210
+ # :default_style => :normal
211
+ # user.avatar.url # => "/avatars/23/normal_me.png"
212
+ # * +whiny+: Will raise an error if Paperclip cannot post_process an uploaded file due
213
+ # to a command line error. This will override the global setting for this attachment.
214
+ # Defaults to true. This option used to be called :whiny_thumbanils, but this is
215
+ # deprecated.
216
+ # * +convert_options+: When creating thumbnails, use this free-form options
217
+ # array to pass in various convert command options. Typical options are "-strip" to
218
+ # remove all Exif data from the image (save space for thumbnails and avatars) or
219
+ # "-depth 8" to specify the bit depth of the resulting conversion. See ImageMagick
220
+ # convert documentation for more options: (http://www.imagemagick.org/script/convert.php)
221
+ # Note that this option takes a hash of options, each of which correspond to the style
222
+ # of thumbnail being generated. You can also specify :all as a key, which will apply
223
+ # to all of the thumbnails being generated. If you specify options for the :original,
224
+ # it would be best if you did not specify destructive options, as the intent of keeping
225
+ # the original around is to regenerate all the thumbnails when requirements change.
226
+ # has_attached_file :avatar, :styles => { :large => "300x300", :negative => "100x100" }
227
+ # :convert_options => {
228
+ # :all => "-strip",
229
+ # :negative => "-negate"
230
+ # }
231
+ # NOTE: While not deprecated yet, it is not recommended to specify options this way.
232
+ # It is recommended that :convert_options option be included in the hash passed to each
233
+ # :styles for compatability with future versions.
234
+ # NOTE: Strings supplied to :convert_options are split on space in order to undergo
235
+ # shell quoting for safety. If your options require a space, please pre-split them
236
+ # and pass an array to :convert_options instead.
237
+ # * +storage+: Chooses the storage backend where the files will be stored. The current
238
+ # choices are :filesystem and :s3. The default is :filesystem. Make sure you read the
239
+ # documentation for Paperclip::Storage::Filesystem and Paperclip::Storage::S3
240
+ # for backend-specific options.
241
+ def has_attached_file name, options = {}
242
+ include InstanceMethods
243
+
244
+ write_inheritable_attribute(:attachment_definitions, {}) if attachment_definitions.nil?
245
+ attachment_definitions[name] = {:validations => []}.merge(options)
246
+
247
+ after_save :save_attached_files
248
+ before_destroy :destroy_attached_files
249
+
250
+ define_paperclip_callbacks :post_process, :"#{name}_post_process"
251
+
252
+ define_method name do |*args|
253
+ a = attachment_for(name)
254
+ (args.length > 0) ? a.to_s(args.first) : a
255
+ end
256
+
257
+ define_method "#{name}=" do |file|
258
+ attachment_for(name).assign(file)
259
+ end
260
+
261
+ define_method "#{name}?" do
262
+ attachment_for(name).file?
263
+ end
264
+
265
+ validates_each(name) do |record, attr, value|
266
+ attachment = record.attachment_for(name)
267
+ attachment.send(:flush_errors)
268
+ end
269
+ end
270
+
271
+ # Places ActiveRecord-style validations on the size of the file assigned. The
272
+ # possible options are:
273
+ # * +in+: a Range of bytes (i.e. +1..1.megabyte+),
274
+ # * +less_than+: equivalent to :in => 0..options[:less_than]
275
+ # * +greater_than+: equivalent to :in => options[:greater_than]..Infinity
276
+ # * +message+: error message to display, use :min and :max as replacements
277
+ # * +if+: A lambda or name of a method on the instance. Validation will only
278
+ # be run is this lambda or method returns true.
279
+ # * +unless+: Same as +if+ but validates if lambda or method returns false.
280
+ def validates_attachment_size name, options = {}
281
+ min = options[:greater_than] || (options[:in] && options[:in].first) || 0
282
+ max = options[:less_than] || (options[:in] && options[:in].last) || (1.0/0)
283
+ range = (min..max)
284
+ message = options[:message] || "file size must be between :min and :max bytes."
285
+ message = message.call if message.respond_to?(:call)
286
+ message = message.gsub(/:min/, min.to_s).gsub(/:max/, max.to_s)
287
+
288
+ validates_inclusion_of :"#{name}_file_size",
289
+ :in => range,
290
+ :message => message,
291
+ :if => options[:if],
292
+ :unless => options[:unless],
293
+ :allow_nil => true
294
+ end
295
+
296
+ # Adds errors if thumbnail creation fails. The same as specifying :whiny_thumbnails => true.
297
+ def validates_attachment_thumbnails name, options = {}
298
+ warn('[DEPRECATION] validates_attachment_thumbnail is deprecated. ' +
299
+ 'This validation is on by default and will be removed from future versions. ' +
300
+ 'If you wish to turn it off, supply :whiny => false in your definition.')
301
+ attachment_definitions[name][:whiny_thumbnails] = true
302
+ end
303
+
304
+ # Places ActiveRecord-style validations on the presence of a file.
305
+ # Options:
306
+ # * +if+: A lambda or name of a method on the instance. Validation will only
307
+ # be run is this lambda or method returns true.
308
+ # * +unless+: Same as +if+ but validates if lambda or method returns false.
309
+ def validates_attachment_presence name, options = {}
310
+ message = options[:message] || "must be set."
311
+ validates_presence_of :"#{name}_file_name",
312
+ :message => message,
313
+ :if => options[:if],
314
+ :unless => options[:unless]
315
+ end
316
+
317
+ # Places ActiveRecord-style validations on the content type of the file
318
+ # assigned. The possible options are:
319
+ # * +content_type+: Allowed content types. Can be a single content type
320
+ # or an array. Each type can be a String or a Regexp. It should be
321
+ # noted that Internet Explorer upload files with content_types that you
322
+ # may not expect. For example, JPEG images are given image/pjpeg and
323
+ # PNGs are image/x-png, so keep that in mind when determining how you
324
+ # match. Allows all by default.
325
+ # * +message+: The message to display when the uploaded file has an invalid
326
+ # content type.
327
+ # * +if+: A lambda or name of a method on the instance. Validation will only
328
+ # be run is this lambda or method returns true.
329
+ # * +unless+: Same as +if+ but validates if lambda or method returns false.
330
+ # NOTE: If you do not specify an [attachment]_content_type field on your
331
+ # model, content_type validation will work _ONLY upon assignment_ and
332
+ # re-validation after the instance has been reloaded will always succeed.
333
+ def validates_attachment_content_type name, options = {}
334
+ validation_options = options.dup
335
+ allowed_types = [validation_options[:content_type]].flatten
336
+ validates_each(:"#{name}_content_type", validation_options) do |record, attr, value|
337
+ if !allowed_types.any?{|t| t === value } && !(value.nil? || value.blank?)
338
+ if record.errors.method(:add).arity == -2
339
+ message = options[:message] || "is not one of #{allowed_types.join(", ")}"
340
+ message = message.call if message.respond_to?(:call)
341
+ record.errors.add(:"#{name}_content_type", message)
342
+ else
343
+ record.errors.add(:"#{name}_content_type", :inclusion, :default => options[:message], :value => value)
344
+ end
345
+ end
346
+ end
347
+ end
348
+
349
+ # Returns the attachment definitions defined by each call to
350
+ # has_attached_file.
351
+ def attachment_definitions
352
+ read_inheritable_attribute(:attachment_definitions)
353
+ end
354
+ end
355
+
356
+ module InstanceMethods #:nodoc:
357
+ def attachment_for name
358
+ @_paperclip_attachments ||= {}
359
+ @_paperclip_attachments[name] ||= Attachment.new(name, self, self.class.attachment_definitions[name])
360
+ end
361
+
362
+ def each_attachment
363
+ self.class.attachment_definitions.each do |name, definition|
364
+ yield(name, attachment_for(name))
365
+ end
366
+ end
367
+
368
+ def save_attached_files
369
+ Paperclip.log("Saving attachments.")
370
+ each_attachment do |name, attachment|
371
+ attachment.send(:save)
372
+ end
373
+ end
374
+
375
+ def destroy_attached_files
376
+ Paperclip.log("Deleting attachments.")
377
+ each_attachment do |name, attachment|
378
+ attachment.send(:queue_existing_for_delete)
379
+ attachment.send(:flush_deletes)
380
+ end
381
+ end
382
+ end
383
+
384
+ end
@@ -0,0 +1,378 @@
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
+ include IOStream
8
+
9
+ def self.default_options
10
+ @default_options ||= {
11
+ :url => "/system/:attachment/:id/:style/:filename",
12
+ :path => ":rails_root/public:url",
13
+ :styles => {},
14
+ :processors => [:thumbnail],
15
+ :convert_options => {},
16
+ :default_url => "/:attachment/:style/missing.png",
17
+ :default_style => :original,
18
+ :storage => :filesystem,
19
+ :use_timestamp => true,
20
+ :whiny => Paperclip.options[:whiny] || Paperclip.options[:whiny_thumbnails],
21
+ :use_default_time_zone => true,
22
+ :hash_digest => "SHA1",
23
+ :hash_data => ":class/:attachment/:id/:style/:updated_at"
24
+ }
25
+ end
26
+
27
+ attr_reader :name, :instance, :default_style, :convert_options, :queued_for_write, :whiny, :options
28
+ attr_accessor :post_processing
29
+
30
+ # Creates an Attachment object. +name+ is the name of the attachment,
31
+ # +instance+ is the ActiveRecord object instance it's attached to, and
32
+ # +options+ is the same as the hash passed to +has_attached_file+.
33
+ def initialize name, instance, options = {}
34
+ @name = name
35
+ @instance = instance
36
+
37
+ options = self.class.default_options.merge(options)
38
+
39
+ @url = options[:url]
40
+ @url = @url.call(self) if @url.is_a?(Proc)
41
+ @path = options[:path]
42
+ @path = @path.call(self) if @path.is_a?(Proc)
43
+ @styles = options[:styles]
44
+ @normalized_styles = nil
45
+ @default_url = options[:default_url]
46
+ @default_style = options[:default_style]
47
+ @storage = options[:storage]
48
+ @use_timestamp = options[:use_timestamp]
49
+ @whiny = options[:whiny_thumbnails] || options[:whiny]
50
+ @use_default_time_zone = options[:use_default_time_zone]
51
+ @hash_digest = options[:hash_digest]
52
+ @hash_data = options[:hash_data]
53
+ @hash_secret = options[:hash_secret]
54
+ @convert_options = options[:convert_options]
55
+ @processors = options[:processors]
56
+ @options = options
57
+ @post_processing = true
58
+ @queued_for_delete = []
59
+ @queued_for_write = {}
60
+ @errors = {}
61
+ @dirty = false
62
+
63
+ initialize_storage
64
+ end
65
+
66
+ def styles
67
+ if @styles.respond_to?(:call) || !@normalized_styles
68
+ @normalized_styles = {}
69
+ (@styles.respond_to?(:call) ? @styles.call(self) : @styles).each do |name, args|
70
+ @normalized_styles[name] = Paperclip::Style.new(name, args.dup, self)
71
+ end
72
+ end
73
+ @normalized_styles
74
+ end
75
+
76
+ def processors
77
+ @processors.respond_to?(:call) ? @processors.call(instance) : @processors
78
+ end
79
+
80
+ # What gets called when you call instance.attachment = File. It clears
81
+ # errors, assigns attributes, and processes the file. It
82
+ # also queues up the previous file for deletion, to be flushed away on
83
+ # #save of its host. In addition to form uploads, you can also assign
84
+ # another Paperclip attachment:
85
+ # new_user.avatar = old_user.avatar
86
+ def assign uploaded_file
87
+ ensure_required_accessors!
88
+
89
+ if uploaded_file.is_a?(Paperclip::Attachment)
90
+ uploaded_file = uploaded_file.to_file(:original)
91
+ close_uploaded_file = uploaded_file.respond_to?(:close)
92
+ end
93
+
94
+ return nil unless valid_assignment?(uploaded_file)
95
+
96
+ uploaded_file.binmode if uploaded_file.respond_to? :binmode
97
+ self.clear
98
+
99
+ return nil if uploaded_file.nil?
100
+
101
+ @queued_for_write[:original] = to_tempfile(uploaded_file)
102
+ instance_write(:file_name, uploaded_file.original_filename.strip)
103
+ instance_write(:content_type, uploaded_file.content_type.to_s.strip)
104
+ instance_write(:file_size, uploaded_file.size.to_i)
105
+ instance_write(:fingerprint, generate_fingerprint(uploaded_file))
106
+ instance_write(:updated_at, Time.now)
107
+
108
+ @dirty = true
109
+
110
+ post_process if @post_processing
111
+
112
+ # Reset the file size if the original file was reprocessed.
113
+ instance_write(:file_size, @queued_for_write[:original].size.to_i)
114
+ instance_write(:fingerprint, generate_fingerprint(@queued_for_write[:original]))
115
+ ensure
116
+ uploaded_file.close if close_uploaded_file
117
+ end
118
+
119
+ # Returns the public URL of the attachment, with a given style. Note that
120
+ # this does not necessarily need to point to a file that your web server
121
+ # can access and can point to an action in your app, if you need fine
122
+ # grained security. This is not recommended if you don't need the
123
+ # security, however, for performance reasons. Set use_timestamp to false
124
+ # if you want to stop the attachment update time appended to the url
125
+ def url(style_name = default_style, use_timestamp = @use_timestamp)
126
+ url = original_filename.nil? ? interpolate(@default_url, style_name) : interpolate(@url, style_name)
127
+ use_timestamp && updated_at ? [url, updated_at].compact.join(url.include?("?") ? "&" : "?") : url
128
+ end
129
+
130
+ # Returns the path of the attachment as defined by the :path option. If the
131
+ # file is stored in the filesystem the path refers to the path of the file
132
+ # on disk. If the file is stored in S3, the path is the "key" part of the
133
+ # URL, and the :bucket option refers to the S3 bucket.
134
+ def path style_name = default_style
135
+ original_filename.nil? ? nil : interpolate(@path, style_name)
136
+ end
137
+
138
+ # Alias to +url+
139
+ def to_s style_name = default_style
140
+ url(style_name)
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
+ flush_deletes
157
+ flush_writes
158
+ @dirty = false
159
+ true
160
+ end
161
+
162
+ # Clears out the attachment. Has the same effect as previously assigning
163
+ # nil to the attachment. Does NOT save. If you wish to clear AND save,
164
+ # use #destroy.
165
+ def clear
166
+ queue_existing_for_delete
167
+ @errors = {}
168
+ end
169
+
170
+ # Destroys the attachment. Has the same effect as previously assigning
171
+ # nil to the attachment *and saving*. This is permanent. If you wish to
172
+ # wipe out the existing attachment but not save, use #clear.
173
+ def destroy
174
+ clear
175
+ save
176
+ end
177
+
178
+ # Returns the name of the file as originally assigned, and lives in the
179
+ # <attachment>_file_name attribute of the model.
180
+ def original_filename
181
+ instance_read(:file_name)
182
+ end
183
+
184
+ # Returns the size of the file as originally assigned, and lives in the
185
+ # <attachment>_file_size attribute of the model.
186
+ def size
187
+ instance_read(:file_size) || (@queued_for_write[:original] && @queued_for_write[:original].size)
188
+ end
189
+
190
+ # Returns the hash of the file as originally assigned, and lives in the
191
+ # <attachment>_fingerprint attribute of the model.
192
+ def fingerprint
193
+ instance_read(:fingerprint) || (@queued_for_write[:original] && generate_fingerprint(@queued_for_write[:original]))
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_f.to_i
207
+ end
208
+
209
+ # The time zone to use for timestamp interpolation. Using the default
210
+ # time zone ensures that results are consistent across all threads.
211
+ def time_zone
212
+ @use_default_time_zone ? Time.zone_default : Time.zone
213
+ end
214
+
215
+ # Returns a unique hash suitable for obfuscating the URL of an otherwise
216
+ # publicly viewable attachment.
217
+ def hash(style_name = default_style)
218
+ raise ArgumentError, "Unable to generate hash without :hash_secret" unless @hash_secret
219
+ require 'openssl' unless defined?(OpenSSL)
220
+ data = interpolate(@hash_data, style_name)
221
+ OpenSSL::HMAC.hexdigest(OpenSSL::Digest.const_get(@hash_digest).new, @hash_secret, data)
222
+ end
223
+
224
+ def generate_fingerprint(source)
225
+ data = source.read
226
+ source.rewind if source.respond_to?(:rewind)
227
+ Digest::MD5.hexdigest(data)
228
+ end
229
+
230
+ # Paths and URLs can have a number of variables interpolated into them
231
+ # to vary the storage location based on name, id, style, class, etc.
232
+ # This method is a deprecated access into supplying and retrieving these
233
+ # interpolations. Future access should use either Paperclip.interpolates
234
+ # or extend the Paperclip::Interpolations module directly.
235
+ def self.interpolations
236
+ warn('[DEPRECATION] Paperclip::Attachment.interpolations is deprecated ' +
237
+ 'and will be removed from future versions. ' +
238
+ 'Use Paperclip.interpolates instead')
239
+ Paperclip::Interpolations
240
+ end
241
+
242
+ # This method really shouldn't be called that often. It's expected use is
243
+ # in the paperclip:refresh rake task and that's it. It will regenerate all
244
+ # thumbnails forcefully, by reobtaining the original file and going through
245
+ # the post-process again.
246
+ def reprocess!(*style_args)
247
+ new_original = Tempfile.new("paperclip-reprocess")
248
+ new_original.binmode
249
+ if old_original = to_file(:original)
250
+ new_original.write( old_original.respond_to?(:get) ? old_original.get : old_original.read )
251
+ new_original.rewind
252
+
253
+ @queued_for_write = { :original => new_original }
254
+ post_process(*style_args)
255
+
256
+ old_original.close if old_original.respond_to?(:close)
257
+
258
+ save
259
+ else
260
+ true
261
+ end
262
+ rescue Errno::EACCES => e
263
+ warn "#{e} - skipping file"
264
+ false
265
+ end
266
+
267
+ # Returns true if a file has been assigned.
268
+ def file?
269
+ !original_filename.blank?
270
+ end
271
+
272
+ alias :present? :file?
273
+
274
+ # Writes the attachment-specific attribute on the instance. For example,
275
+ # instance_write(:file_name, "me.jpg") will write "me.jpg" to the instance's
276
+ # "avatar_file_name" field (assuming the attachment is called avatar).
277
+ def instance_write(attr, value)
278
+ setter = :"#{name}_#{attr}="
279
+ responds = instance.respond_to?(setter)
280
+ self.instance_variable_set("@_#{setter.to_s.chop}", value)
281
+ instance.send(setter, value) if responds || attr.to_s == "file_name"
282
+ end
283
+
284
+ # Reads the attachment-specific attribute on the instance. See instance_write
285
+ # for more details.
286
+ def instance_read(attr)
287
+ getter = :"#{name}_#{attr}"
288
+ responds = instance.respond_to?(getter)
289
+ cached = self.instance_variable_get("@_#{getter}")
290
+ return cached if cached
291
+ instance.send(getter) if responds || attr.to_s == "file_name"
292
+ end
293
+
294
+ private
295
+
296
+ def ensure_required_accessors! #:nodoc:
297
+ %w(file_name).each do |field|
298
+ unless @instance.respond_to?("#{name}_#{field}") && @instance.respond_to?("#{name}_#{field}=")
299
+ raise PaperclipError.new("#{@instance.class} model missing required attr_accessor for '#{name}_#{field}'")
300
+ end
301
+ end
302
+ end
303
+
304
+ def log message #:nodoc:
305
+ Paperclip.log(message)
306
+ end
307
+
308
+ def valid_assignment? file #:nodoc:
309
+ file.nil? || (file.respond_to?(:original_filename) && file.respond_to?(:content_type))
310
+ end
311
+
312
+ def initialize_storage #:nodoc:
313
+ storage_class_name = @storage.to_s.capitalize
314
+ begin
315
+ @storage_module = Paperclip::Storage.const_get(storage_class_name)
316
+ rescue NameError
317
+ raise StorageMethodNotFound, "Cannot load storage module '#{storage_class_name}'"
318
+ end
319
+ self.extend(@storage_module)
320
+ end
321
+
322
+ def extra_options_for(style) #:nodoc:
323
+ all_options = convert_options[:all]
324
+ all_options = all_options.call(instance) if all_options.respond_to?(:call)
325
+ style_options = convert_options[style]
326
+ style_options = style_options.call(instance) if style_options.respond_to?(:call)
327
+
328
+ [ style_options, all_options ].compact.join(" ")
329
+ end
330
+
331
+ def post_process(*style_args) #:nodoc:
332
+ return if @queued_for_write[:original].nil?
333
+ instance.run_paperclip_callbacks(:post_process) do
334
+ instance.run_paperclip_callbacks(:"#{name}_post_process") do
335
+ post_process_styles(*style_args)
336
+ end
337
+ end
338
+ end
339
+
340
+ def post_process_styles(*style_args) #:nodoc:
341
+ styles.each do |name, style|
342
+ begin
343
+ if style_args.empty? || style_args.include?(name)
344
+ raise RuntimeError.new("Style #{name} has no processors defined.") if style.processors.blank?
345
+ @queued_for_write[name] = style.processors.inject(@queued_for_write[:original]) do |file, processor|
346
+ Paperclip.processor(processor).make(file, style.processor_options, self)
347
+ end
348
+ end
349
+ rescue PaperclipError => e
350
+ log("An error was received while processing: #{e.inspect}")
351
+ (@errors[:processing] ||= []) << e.message if @whiny
352
+ end
353
+ end
354
+ end
355
+
356
+ def interpolate pattern, style_name = default_style #:nodoc:
357
+ Paperclip::Interpolations.interpolate(pattern, self, style_name)
358
+ end
359
+
360
+ def queue_existing_for_delete #:nodoc:
361
+ return unless file?
362
+ @queued_for_delete += [:original, *styles.keys].uniq.map do |style|
363
+ path(style) if exists?(style)
364
+ end.compact
365
+ instance_write(:file_name, nil)
366
+ instance_write(:content_type, nil)
367
+ instance_write(:file_size, nil)
368
+ instance_write(:updated_at, nil)
369
+ end
370
+
371
+ def flush_errors #:nodoc:
372
+ @errors.each do |error, message|
373
+ [message].flatten.each {|m| instance.errors.add(name, m) }
374
+ end
375
+ end
376
+
377
+ end
378
+ end