paperclip-v2_7-patched-ruby-1_8_6 2.7.5

Sign up to get free protection for your applications and to get access to all the features.
Files changed (107) hide show
  1. checksums.yaml +7 -0
  2. data/.gitignore +23 -0
  3. data/.travis.yml +14 -0
  4. data/Appraisals +20 -0
  5. data/CONTRIBUTING.md +38 -0
  6. data/Gemfile +5 -0
  7. data/LICENSE +26 -0
  8. data/NEWS +69 -0
  9. data/README.md +444 -0
  10. data/Rakefile +41 -0
  11. data/cucumber/paperclip_steps.rb +6 -0
  12. data/features/basic_integration.feature +48 -0
  13. data/features/rake_tasks.feature +68 -0
  14. data/features/step_definitions/attachment_steps.rb +65 -0
  15. data/features/step_definitions/html_steps.rb +15 -0
  16. data/features/step_definitions/rails_steps.rb +193 -0
  17. data/features/step_definitions/s3_steps.rb +14 -0
  18. data/features/step_definitions/web_steps.rb +209 -0
  19. data/features/support/env.rb +8 -0
  20. data/features/support/fakeweb.rb +3 -0
  21. data/features/support/fixtures/.boot_config.rb.swo +0 -0
  22. data/features/support/fixtures/boot_config.txt +15 -0
  23. data/features/support/fixtures/gemfile.txt +5 -0
  24. data/features/support/fixtures/preinitializer.txt +20 -0
  25. data/features/support/paths.rb +28 -0
  26. data/features/support/rails.rb +46 -0
  27. data/features/support/selectors.rb +19 -0
  28. data/gemfiles/rails2.gemfile +9 -0
  29. data/gemfiles/rails3.gemfile +9 -0
  30. data/gemfiles/rails3_1.gemfile +9 -0
  31. data/gemfiles/rails3_2.gemfile +9 -0
  32. data/generators/paperclip/USAGE +5 -0
  33. data/generators/paperclip/paperclip_generator.rb +27 -0
  34. data/generators/paperclip/templates/paperclip_migration.rb.erb +19 -0
  35. data/init.rb +4 -0
  36. data/lib/generators/paperclip/USAGE +8 -0
  37. data/lib/generators/paperclip/paperclip_generator.rb +33 -0
  38. data/lib/generators/paperclip/templates/paperclip_migration.rb.erb +19 -0
  39. data/lib/paperclip.rb +493 -0
  40. data/lib/paperclip/attachment.rb +491 -0
  41. data/lib/paperclip/attachment_options.rb +10 -0
  42. data/lib/paperclip/callback_compatibility.rb +61 -0
  43. data/lib/paperclip/geometry.rb +120 -0
  44. data/lib/paperclip/interpolations.rb +174 -0
  45. data/lib/paperclip/iostream.rb +45 -0
  46. data/lib/paperclip/matchers.rb +64 -0
  47. data/lib/paperclip/matchers/have_attached_file_matcher.rb +57 -0
  48. data/lib/paperclip/matchers/validate_attachment_content_type_matcher.rb +81 -0
  49. data/lib/paperclip/matchers/validate_attachment_presence_matcher.rb +54 -0
  50. data/lib/paperclip/matchers/validate_attachment_size_matcher.rb +95 -0
  51. data/lib/paperclip/missing_attachment_styles.rb +87 -0
  52. data/lib/paperclip/processor.rb +58 -0
  53. data/lib/paperclip/railtie.rb +35 -0
  54. data/lib/paperclip/schema.rb +39 -0
  55. data/lib/paperclip/storage.rb +3 -0
  56. data/lib/paperclip/storage/filesystem.rb +81 -0
  57. data/lib/paperclip/storage/fog.rb +191 -0
  58. data/lib/paperclip/storage/s3.rb +351 -0
  59. data/lib/paperclip/style.rb +103 -0
  60. data/lib/paperclip/thumbnail.rb +105 -0
  61. data/lib/paperclip/upfile.rb +64 -0
  62. data/lib/paperclip/url_generator.rb +64 -0
  63. data/lib/paperclip/version.rb +3 -0
  64. data/lib/tasks/paperclip.rake +101 -0
  65. data/paperclip.gemspec +41 -0
  66. data/rails/init.rb +2 -0
  67. data/shoulda_macros/paperclip.rb +124 -0
  68. data/test/attachment_options_test.rb +40 -0
  69. data/test/attachment_test.rb +1211 -0
  70. data/test/database.yml +4 -0
  71. data/test/fixtures/12k.png +0 -0
  72. data/test/fixtures/50x50.png +0 -0
  73. data/test/fixtures/5k.png +0 -0
  74. data/test/fixtures/animated.gif +0 -0
  75. data/test/fixtures/bad.png +1 -0
  76. data/test/fixtures/fog.yml +8 -0
  77. data/test/fixtures/s3.yml +8 -0
  78. data/test/fixtures/spaced file.png +0 -0
  79. data/test/fixtures/text.txt +1 -0
  80. data/test/fixtures/twopage.pdf +0 -0
  81. data/test/fixtures/uppercase.PNG +0 -0
  82. data/test/geometry_test.rb +206 -0
  83. data/test/helper.rb +181 -0
  84. data/test/integration_test.rb +652 -0
  85. data/test/interpolations_test.rb +219 -0
  86. data/test/iostream_test.rb +71 -0
  87. data/test/matchers/have_attached_file_matcher_test.rb +24 -0
  88. data/test/matchers/validate_attachment_content_type_matcher_test.rb +110 -0
  89. data/test/matchers/validate_attachment_presence_matcher_test.rb +47 -0
  90. data/test/matchers/validate_attachment_size_matcher_test.rb +72 -0
  91. data/test/paperclip_missing_attachment_styles_test.rb +96 -0
  92. data/test/paperclip_test.rb +409 -0
  93. data/test/processor_test.rb +10 -0
  94. data/test/schema_test.rb +98 -0
  95. data/test/storage/filesystem_test.rb +62 -0
  96. data/test/storage/fog_test.rb +280 -0
  97. data/test/storage/s3_live_test.rb +138 -0
  98. data/test/storage/s3_test.rb +1093 -0
  99. data/test/style_test.rb +215 -0
  100. data/test/support/mock_attachment.rb +22 -0
  101. data/test/support/mock_interpolator.rb +24 -0
  102. data/test/support/mock_model.rb +2 -0
  103. data/test/support/mock_url_generator_builder.rb +27 -0
  104. data/test/thumbnail_test.rb +396 -0
  105. data/test/upfile_test.rb +53 -0
  106. data/test/url_generator_test.rb +187 -0
  107. metadata +374 -0
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,493 @@
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/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/attachment_options'
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. The options available are:
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, command_path].flatten.compact.uniq
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
+ unscope_method = class_for(klass).respond_to?(:unscoped) ? :unscoped : :with_exclusive_scope
144
+ class_for(klass).send(unscope_method) do
145
+ class_for(klass).find(:all, :order => 'id').each do |instance|
146
+ yield(instance) if instance.send(:"#{name}?")
147
+ end
148
+ end
149
+ end
150
+
151
+ # Log a paperclip-specific line. This will logs to STDOUT
152
+ # by default. Set Paperclip.options[:log] to false to turn off.
153
+ def log message
154
+ logger.info("[paperclip] #{message}") if logging?
155
+ end
156
+
157
+ def logger #:nodoc:
158
+ @logger ||= options[:logger] || Logger.new(STDOUT)
159
+ end
160
+
161
+ def logger=(logger)
162
+ @logger = logger
163
+ end
164
+
165
+ def logging? #:nodoc:
166
+ options[:log]
167
+ end
168
+
169
+ def class_for(class_name)
170
+ # Ruby 1.9 introduces an inherit argument for Module#const_get and
171
+ # #const_defined? and changes their default behavior.
172
+ # https://github.com/rails/rails/blob/v3.0.9/activesupport/lib/active_support/inflector/methods.rb#L89
173
+ if Module.method(:const_get).arity == 1
174
+ class_name.split('::').inject(Object) do |klass, partial_class_name|
175
+ klass.const_defined?(partial_class_name) ? klass.const_get(partial_class_name) : klass.const_missing(partial_class_name)
176
+ end
177
+ else
178
+ class_name.split('::').inject(Object) do |klass, partial_class_name|
179
+ klass.const_defined?(partial_class_name) ? klass.const_get(partial_class_name, false) : klass.const_missing(partial_class_name)
180
+ end
181
+ end
182
+ rescue ArgumentError => e
183
+ # Sadly, we need to capture ArgumentError here because Rails 2.3.x
184
+ # ActiveSupport dependency management will try to the constant inherited
185
+ # from Object, and fail miserably with "Object is not missing constant X" error
186
+ # https://github.com/rails/rails/blob/v2.3.12/activesupport/lib/active_support/dependencies.rb#L124
187
+ if e.message =~ /is not missing constant/
188
+ raise NameError, "uninitialized constant #{class_name}"
189
+ else
190
+ raise e
191
+ end
192
+ end
193
+
194
+ def check_for_path_clash(name,path,klass)
195
+ @names_path ||= {}
196
+ default_path = path || Attachment.default_options[:path]
197
+ if @names_path[name] && @names_path[name][:path] == default_path && @names_path[name][:class] != klass && @names_path[name][:path] !~ /:class/
198
+ log("Duplicate path for #{name} with #{default_path}. This will clash with attachment defined in #{@names_path[name][:class]} class")
199
+ end
200
+ @names_path[name] = {:path => default_path, :class => klass}
201
+ end
202
+
203
+
204
+ def reset_duplicate_clash_check!
205
+ @names_url = nil
206
+ end
207
+ end
208
+
209
+ class PaperclipError < StandardError #:nodoc:
210
+ end
211
+
212
+ class StorageMethodNotFound < PaperclipError
213
+ end
214
+
215
+ class CommandNotFoundError < PaperclipError
216
+ end
217
+
218
+ class NotIdentifiedByImageMagickError < PaperclipError #:nodoc:
219
+ end
220
+
221
+ class InfiniteInterpolationError < PaperclipError #:nodoc:
222
+ end
223
+
224
+ module Glue
225
+ def self.included base #:nodoc:
226
+ base.extend ClassMethods
227
+ base.class_attribute :attachment_definitions if base.respond_to?(:class_attribute)
228
+ if base.respond_to?(:set_callback)
229
+ base.send :include, Paperclip::CallbackCompatability::Rails3
230
+ else
231
+ base.send :include, Paperclip::CallbackCompatability::Rails21
232
+ end
233
+ end
234
+ end
235
+
236
+ module ClassMethods
237
+ # +has_attached_file+ gives the class it is called on an attribute that maps to a file. This
238
+ # is typically a file stored somewhere on the filesystem and has been uploaded by a user.
239
+ # The attribute returns a Paperclip::Attachment object which handles the management of
240
+ # that file. The intent is to make the attachment as much like a normal attribute. The
241
+ # thumbnails will be created when the new file is assigned, but they will *not* be saved
242
+ # until +save+ is called on the record. Likewise, if the attribute is set to +nil+ is
243
+ # called on it, the attachment will *not* be deleted until +save+ is called. See the
244
+ # Paperclip::Attachment documentation for more specifics. There are a number of options
245
+ # you can set to change the behavior of a Paperclip attachment:
246
+ # * +url+: The full URL of where the attachment is publically accessible. This can just
247
+ # as easily point to a directory served directly through Apache as it can to an action
248
+ # that can control permissions. You can specify the full domain and path, but usually
249
+ # just an absolute path is sufficient. The leading slash *must* be included manually for
250
+ # absolute paths. The default value is
251
+ # "/system/:attachment/:id/:style/:filename". See
252
+ # Paperclip::Attachment#interpolate for more information on variable interpolaton.
253
+ # :url => "/:class/:attachment/:id/:style_:filename"
254
+ # :url => "http://some.other.host/stuff/:class/:id_:extension"
255
+ # * +default_url+: The URL that will be returned if there is no attachment assigned.
256
+ # This field is interpolated just as the url is. The default value is
257
+ # "/:attachment/:style/missing.png"
258
+ # has_attached_file :avatar, :default_url => "/images/default_:style_avatar.png"
259
+ # User.new.avatar_url(:small) # => "/images/default_small_avatar.png"
260
+ # * +styles+: A hash of thumbnail styles and their geometries. You can find more about
261
+ # geometry strings at the ImageMagick website
262
+ # (http://www.imagemagick.org/script/command-line-options.php#resize). Paperclip
263
+ # also adds the "#" option (e.g. "50x50#"), which will resize the image to fit maximally
264
+ # inside the dimensions and then crop the rest off (weighted at the center). The
265
+ # default value is to generate no thumbnails.
266
+ # * +default_style+: The thumbnail style that will be used by default URLs.
267
+ # Defaults to +original+.
268
+ # has_attached_file :avatar, :styles => { :normal => "100x100#" },
269
+ # :default_style => :normal
270
+ # user.avatar.url # => "/avatars/23/normal_me.png"
271
+ # * +keep_old_files+: Keep the existing attachment files (original + resized) from
272
+ # being automatically deleted when an attachment is cleared or updated.
273
+ # Defaults to +false+.#
274
+ # * +whiny+: Will raise an error if Paperclip cannot post_process an uploaded file due
275
+ # to a command line error. This will override the global setting for this attachment.
276
+ # Defaults to true. This option used to be called :whiny_thumbanils, but this is
277
+ # deprecated.
278
+ # * +convert_options+: When creating thumbnails, use this free-form options
279
+ # array to pass in various convert command options. Typical options are "-strip" to
280
+ # remove all Exif data from the image (save space for thumbnails and avatars) or
281
+ # "-depth 8" to specify the bit depth of the resulting conversion. See ImageMagick
282
+ # convert documentation for more options: (http://www.imagemagick.org/script/convert.php)
283
+ # Note that this option takes a hash of options, each of which correspond to the style
284
+ # of thumbnail being generated. You can also specify :all as a key, which will apply
285
+ # to all of the thumbnails being generated. If you specify options for the :original,
286
+ # it would be best if you did not specify destructive options, as the intent of keeping
287
+ # the original around is to regenerate all the thumbnails when requirements change.
288
+ # has_attached_file :avatar, :styles => { :large => "300x300", :negative => "100x100" }
289
+ # :convert_options => {
290
+ # :all => "-strip",
291
+ # :negative => "-negate"
292
+ # }
293
+ # NOTE: While not deprecated yet, it is not recommended to specify options this way.
294
+ # It is recommended that :convert_options option be included in the hash passed to each
295
+ # :styles for compatibility with future versions.
296
+ # NOTE: Strings supplied to :convert_options are split on space in order to undergo
297
+ # shell quoting for safety. If your options require a space, please pre-split them
298
+ # and pass an array to :convert_options instead.
299
+ # * +storage+: Chooses the storage backend where the files will be stored. The current
300
+ # choices are :filesystem, :fog and :s3. The default is :filesystem. Make sure you read the
301
+ # documentation for Paperclip::Storage::Filesystem, Paperclip::Storage::Fog and Paperclip::Storage::S3
302
+ # for backend-specific options.
303
+ #
304
+ # It's also possible for you to dynamically define your interpolation string for :url,
305
+ # :default_url, and :path in your model by passing a method name as a symbol as a argument
306
+ # for your has_attached_file definition:
307
+ #
308
+ # class Person
309
+ # has_attached_file :avatar, :default_url => :default_url_by_gender
310
+ #
311
+ # private
312
+ #
313
+ # def default_url_by_gender
314
+ # "/assets/avatars/default_#{gender}.png"
315
+ # end
316
+ # end
317
+ def has_attached_file name, options = {}
318
+ include InstanceMethods
319
+
320
+ if attachment_definitions.nil?
321
+ if respond_to?(:class_attribute)
322
+ self.attachment_definitions = {}
323
+ else
324
+ write_inheritable_attribute(:attachment_definitions, {})
325
+ end
326
+ else
327
+ if respond_to?(:class_attribute)
328
+ self.attachment_definitions = self.attachment_definitions.dup
329
+ else
330
+ write_inheritable_attribute(:attachment_definitions, self.attachment_definitions.dup)
331
+ end
332
+ end
333
+
334
+ attachment_definitions[name] = Paperclip::AttachmentOptions.new(options)
335
+ Paperclip.classes_with_attachments << self.name
336
+ Paperclip.check_for_path_clash(name,attachment_definitions[name][:path],self.name)
337
+
338
+ after_save :save_attached_files
339
+ before_destroy :prepare_for_destroy
340
+ after_destroy :destroy_attached_files
341
+
342
+ define_paperclip_callbacks :post_process, :"#{name}_post_process"
343
+
344
+ define_method name do |*args|
345
+ a = attachment_for(name)
346
+ (args.length > 0) ? a.to_s(args.first) : a
347
+ end
348
+
349
+ define_method "#{name}=" do |file|
350
+ attachment_for(name).assign(file)
351
+ end
352
+
353
+ define_method "#{name}?" do
354
+ attachment_for(name).file?
355
+ end
356
+
357
+ validates_each(name) do |record, attr, value|
358
+ attachment = record.attachment_for(name)
359
+ attachment.send(:flush_errors)
360
+ end
361
+ end
362
+
363
+ # Places ActiveRecord-style validations on the size of the file assigned. The
364
+ # possible options are:
365
+ # * +in+: a Range of bytes (i.e. +1..1.megabyte+),
366
+ # * +less_than+: equivalent to :in => 0..options[:less_than]
367
+ # * +greater_than+: equivalent to :in => options[:greater_than]..Infinity
368
+ # * +message+: error message to display, use :min and :max as replacements
369
+ # * +if+: A lambda or name of an instance method. Validation will only
370
+ # be run if this lambda or method returns true.
371
+ # * +unless+: Same as +if+ but validates if lambda or method returns false.
372
+ def validates_attachment_size name, options = {}
373
+ min = options[:greater_than] || (options[:in] && options[:in].first) || 0
374
+ max = options[:less_than] || (options[:in] && options[:in].last) || (1.0/0)
375
+ range = (min..max)
376
+ message = options[:message] || "must be between :min and :max bytes"
377
+ message = message.call if message.respond_to?(:call)
378
+ message = message.gsub(/:min/, min.to_s).gsub(/:max/, max.to_s)
379
+
380
+ validates_inclusion_of :"#{name}_file_size",
381
+ :in => range,
382
+ :message => message,
383
+ :if => options[:if],
384
+ :unless => options[:unless],
385
+ :allow_nil => true
386
+ end
387
+
388
+ # Adds errors if thumbnail creation fails. The same as specifying :whiny_thumbnails => true.
389
+ def validates_attachment_thumbnails name, options = {}
390
+ warn('[DEPRECATION] validates_attachment_thumbnail is deprecated. ' +
391
+ 'This validation is on by default and will be removed from future versions. ' +
392
+ 'If you wish to turn it off, supply :whiny => false in your definition.')
393
+ attachment_definitions[name][:whiny_thumbnails] = true
394
+ end
395
+
396
+ # Places ActiveRecord-style validations on the presence of a file.
397
+ # Options:
398
+ # * +if+: A lambda or name of an instance method. Validation will only
399
+ # be run if this lambda or method returns true.
400
+ # * +unless+: Same as +if+ but validates if lambda or method returns false.
401
+ def validates_attachment_presence name, options = {}
402
+ message = options[:message] || :empty
403
+ validates_each :"#{name}_file_name" do |record, attr, value|
404
+ if_clause_passed = options[:if].nil? || (options[:if].respond_to?(:call) ? options[:if].call(record) != false : record.send(options[:if]))
405
+ unless_clause_passed = options[:unless].nil? || (options[:unless].respond_to?(:call) ? !!options[:unless].call(record) == false : !record.send(options[:unless]))
406
+ if if_clause_passed && unless_clause_passed && value.blank?
407
+ record.errors.add(name, message)
408
+ record.errors.add("#{name}_file_name", message)
409
+ end
410
+ end
411
+ end
412
+
413
+ # Places ActiveRecord-style validations on the content type of the file
414
+ # assigned. The possible options are:
415
+ # * +content_type+: Allowed content types. Can be a single content type
416
+ # or an array. Each type can be a String or a Regexp. It should be
417
+ # noted that Internet Explorer uploads files with content_types that you
418
+ # may not expect. For example, JPEG images are given image/pjpeg and
419
+ # PNGs are image/x-png, so keep that in mind when determining how you
420
+ # match. Allows all by default.
421
+ # * +message+: The message to display when the uploaded file has an invalid
422
+ # content type.
423
+ # * +if+: A lambda or name of an instance method. Validation will only
424
+ # be run is this lambda or method returns true.
425
+ # * +unless+: Same as +if+ but validates if lambda or method returns false.
426
+ # NOTE: If you do not specify an [attachment]_content_type field on your
427
+ # model, content_type validation will work _ONLY upon assignment_ and
428
+ # re-validation after the instance has been reloaded will always succeed.
429
+ # You'll still need to have a virtual attribute (created by +attr_accessor+)
430
+ # name +[attachment]_content_type+ to be able to use this validator.
431
+ def validates_attachment_content_type name, options = {}
432
+ validation_options = options.dup
433
+ allowed_types = [validation_options[:content_type]].flatten
434
+ validates_each(:"#{name}_content_type", validation_options) do |record, attr, value|
435
+ if !allowed_types.any?{|t| t === value } && !(value.nil? || value.blank?)
436
+ if record.errors.method(:add).arity == -2
437
+ message = options[:message] || "is not one of #{allowed_types.join(", ")}"
438
+ message = message.call if message.respond_to?(:call)
439
+ record.errors.add(:"#{name}_content_type", message)
440
+ else
441
+ record.errors.add(:"#{name}_content_type", :inclusion, :default => options[:message], :value => value)
442
+ end
443
+ end
444
+ end
445
+ end
446
+
447
+ # Returns the attachment definitions defined by each call to
448
+ # has_attached_file.
449
+ def attachment_definitions
450
+ if respond_to?(:class_attribute)
451
+ self.attachment_definitions
452
+ else
453
+ read_inheritable_attribute(:attachment_definitions)
454
+ end
455
+ end
456
+ end
457
+
458
+ module InstanceMethods #:nodoc:
459
+ def attachment_for name
460
+ @_paperclip_attachments ||= {}
461
+ @_paperclip_attachments[name] ||= Attachment.new(name, self, self.class.attachment_definitions[name])
462
+ end
463
+
464
+ def each_attachment
465
+ self.class.attachment_definitions.each do |name, definition|
466
+ yield(name, attachment_for(name))
467
+ end
468
+ end
469
+
470
+ def save_attached_files
471
+ Paperclip.log("Saving attachments.")
472
+ each_attachment do |name, attachment|
473
+ attachment.send(:save)
474
+ end
475
+ end
476
+
477
+ def destroy_attached_files
478
+ Paperclip.log("Deleting attachments.")
479
+ each_attachment do |name, attachment|
480
+ attachment.send(:flush_deletes)
481
+ end
482
+ end
483
+
484
+ def prepare_for_destroy
485
+ Paperclip.log("Scheduling attachments for deletion.")
486
+ each_attachment do |name, attachment|
487
+ attachment.send(:queue_existing_for_delete)
488
+ end
489
+ end
490
+
491
+ end
492
+
493
+ end