jmcnevin-paperclip 2.4.5

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