cloudfuji_paperclip 2.4.6

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