winton-attachment_fu 1.0.5

Sign up to get free protection for your applications and to get access to all the features.
Files changed (44) hide show
  1. data/CHANGELOG +35 -0
  2. data/README +186 -0
  3. data/Rakefile +22 -0
  4. data/amazon_s3.yml.tpl +14 -0
  5. data/init.rb +17 -0
  6. data/install.rb +5 -0
  7. data/lib/geometry.rb +93 -0
  8. data/lib/technoweenie/attachment_fu/backends/db_file_backend.rb +39 -0
  9. data/lib/technoweenie/attachment_fu/backends/file_system_backend.rb +101 -0
  10. data/lib/technoweenie/attachment_fu/backends/s3_backend.rb +303 -0
  11. data/lib/technoweenie/attachment_fu/processors/core_image_processor.rb +59 -0
  12. data/lib/technoweenie/attachment_fu/processors/gd2_processor.rb +54 -0
  13. data/lib/technoweenie/attachment_fu/processors/image_science_processor.rb +61 -0
  14. data/lib/technoweenie/attachment_fu/processors/mini_magick_processor.rb +59 -0
  15. data/lib/technoweenie/attachment_fu/processors/rmagick_processor.rb +54 -0
  16. data/lib/technoweenie/attachment_fu.rb +473 -0
  17. data/test/backends/db_file_test.rb +16 -0
  18. data/test/backends/file_system_test.rb +80 -0
  19. data/test/backends/remote/s3_test.rb +119 -0
  20. data/test/base_attachment_tests.rb +77 -0
  21. data/test/basic_test.rb +70 -0
  22. data/test/database.yml +18 -0
  23. data/test/extra_attachment_test.rb +67 -0
  24. data/test/fixtures/attachment.rb +148 -0
  25. data/test/fixtures/files/fake/rails.png +0 -0
  26. data/test/fixtures/files/foo.txt +1 -0
  27. data/test/fixtures/files/rails.png +0 -0
  28. data/test/geometry_test.rb +101 -0
  29. data/test/processors/core_image_test.rb +37 -0
  30. data/test/processors/gd2_test.rb +31 -0
  31. data/test/processors/image_science_test.rb +31 -0
  32. data/test/processors/mini_magick_test.rb +31 -0
  33. data/test/processors/rmagick_test.rb +255 -0
  34. data/test/schema.rb +108 -0
  35. data/test/test_helper.rb +150 -0
  36. data/test/validation_test.rb +55 -0
  37. data/vendor/red_artisan/core_image/filters/color.rb +27 -0
  38. data/vendor/red_artisan/core_image/filters/effects.rb +31 -0
  39. data/vendor/red_artisan/core_image/filters/perspective.rb +25 -0
  40. data/vendor/red_artisan/core_image/filters/quality.rb +25 -0
  41. data/vendor/red_artisan/core_image/filters/scale.rb +47 -0
  42. data/vendor/red_artisan/core_image/filters/watermark.rb +32 -0
  43. data/vendor/red_artisan/core_image/processor.rb +123 -0
  44. metadata +108 -0
@@ -0,0 +1,473 @@
1
+ module Technoweenie # :nodoc:
2
+ module AttachmentFu # :nodoc:
3
+ @@default_processors = %w(ImageScience Rmagick MiniMagick Gd2 CoreImage)
4
+ @@tempfile_path = File.join(RAILS_ROOT, 'tmp', 'attachment_fu')
5
+ @@content_types = ['image/jpeg', 'image/pjpeg', 'image/gif', 'image/png', 'image/x-png', 'image/jpg']
6
+ mattr_reader :content_types, :tempfile_path, :default_processors
7
+ mattr_writer :tempfile_path
8
+
9
+ class ThumbnailError < StandardError; end
10
+ class AttachmentError < StandardError; end
11
+
12
+ module ActMethods
13
+ # Options:
14
+ # * <tt>:content_type</tt> - Allowed content types. Allows all by default. Use :image to allow all standard image types.
15
+ # * <tt>:min_size</tt> - Minimum size allowed. 1 byte is the default.
16
+ # * <tt>:max_size</tt> - Maximum size allowed. 1.megabyte is the default.
17
+ # * <tt>:size</tt> - Range of sizes allowed. (1..1.megabyte) is the default. This overrides the :min_size and :max_size options.
18
+ # * <tt>:resize_to</tt> - Used by RMagick to resize images. Pass either an array of width/height, or a geometry string.
19
+ # * <tt>:thumbnails</tt> - Specifies a set of thumbnails to generate. This accepts a hash of filename suffixes and RMagick resizing options.
20
+ # * <tt>:thumbnail_class</tt> - Set what class to use for thumbnails. This attachment class is used by default.
21
+ # * <tt>:path_prefix</tt> - path to store the uploaded files. Uses public/#{table_name} by default for the filesystem, and just #{table_name}
22
+ # for the S3 backend. Setting this sets the :storage to :file_system.
23
+ # * <tt>:storage</tt> - Use :file_system to specify the attachment data is stored with the file system. Defaults to :db_system.
24
+
25
+ # * <tt>:keep_profile</tt> By default image EXIF data will be stripped to minimize image size. For small thumbnails this proivides important savings. Picture quality is not affected. Set to false if you want to keep the image profile as is. ImageScience will allways keep EXIF data.
26
+ #
27
+ # Examples:
28
+ # has_attachment :max_size => 1.kilobyte
29
+ # has_attachment :size => 1.megabyte..2.megabytes
30
+ # has_attachment :content_type => 'application/pdf'
31
+ # has_attachment :content_type => ['application/pdf', 'application/msword', 'text/plain']
32
+ # has_attachment :content_type => :image, :resize_to => [50,50]
33
+ # has_attachment :content_type => ['application/pdf', :image], :resize_to => 'x50'
34
+ # has_attachment :thumbnails => { :thumb => [50, 50], :geometry => 'x50' }
35
+ # has_attachment :storage => :file_system, :path_prefix => 'public/files'
36
+ # has_attachment :storage => :file_system, :path_prefix => 'public/files',
37
+ # :content_type => :image, :resize_to => [50,50]
38
+ # has_attachment :storage => :file_system, :path_prefix => 'public/files',
39
+ # :thumbnails => { :thumb => [50, 50], :geometry => 'x50' }
40
+ # has_attachment :storage => :s3
41
+ def has_attachment(options = {})
42
+ # this allows you to redefine the acts' options for each subclass, however
43
+ options[:min_size] ||= 1
44
+ options[:max_size] ||= 1.megabyte
45
+ options[:size] ||= (options[:min_size]..options[:max_size])
46
+ options[:thumbnails] ||= {}
47
+ options[:thumbnail_class] ||= self
48
+ options[:s3_access] ||= :public_read
49
+ options[:content_type] = [options[:content_type]].flatten.collect! { |t| t == :image ? Technoweenie::AttachmentFu.content_types : t }.flatten unless options[:content_type].nil?
50
+
51
+ unless options[:thumbnails].is_a?(Hash)
52
+ raise ArgumentError, ":thumbnails option should be a hash: e.g. :thumbnails => { :foo => '50x50' }"
53
+ end
54
+
55
+ extend ClassMethods unless (class << self; included_modules; end).include?(ClassMethods)
56
+ include InstanceMethods unless included_modules.include?(InstanceMethods)
57
+
58
+ parent_options = attachment_options || {}
59
+ # doing these shenanigans so that #attachment_options is available to processors and backends
60
+ self.attachment_options = options
61
+
62
+ attr_accessor :thumbnail_resize_options
63
+
64
+ attachment_options[:storage] ||= (attachment_options[:file_system_path] || attachment_options[:path_prefix]) ? :file_system : :db_file
65
+ attachment_options[:storage] ||= parent_options[:storage]
66
+ attachment_options[:path_prefix] ||= attachment_options[:file_system_path]
67
+ if attachment_options[:path_prefix].nil?
68
+ attachment_options[:path_prefix] = attachment_options[:storage] == :s3 ? table_name : File.join("public", table_name)
69
+ end
70
+ attachment_options[:path_prefix] = attachment_options[:path_prefix][1..-1] if options[:path_prefix].first == '/'
71
+
72
+ with_options :foreign_key => 'parent_id' do |m|
73
+ m.has_many :thumbnails, :class_name => "::#{attachment_options[:thumbnail_class]}"
74
+ m.belongs_to :parent, :class_name => "::#{base_class}" unless options[:thumbnails].empty?
75
+ end
76
+
77
+ storage_mod = Technoweenie::AttachmentFu::Backends.const_get("#{options[:storage].to_s.classify}Backend")
78
+ include storage_mod unless included_modules.include?(storage_mod)
79
+
80
+ case attachment_options[:processor]
81
+ when :none, nil
82
+ processors = Technoweenie::AttachmentFu.default_processors.dup
83
+ begin
84
+ if processors.any?
85
+ attachment_options[:processor] = "#{processors.first}Processor"
86
+ processor_mod = Technoweenie::AttachmentFu::Processors.const_get(attachment_options[:processor])
87
+ include processor_mod unless included_modules.include?(processor_mod)
88
+ end
89
+ rescue Object, Exception
90
+ raise unless load_related_exception?($!)
91
+
92
+ processors.shift
93
+ retry
94
+ end
95
+ else
96
+ begin
97
+ processor_mod = Technoweenie::AttachmentFu::Processors.const_get("#{attachment_options[:processor].to_s.classify}Processor")
98
+ include processor_mod unless included_modules.include?(processor_mod)
99
+ rescue Object, Exception
100
+ raise unless load_related_exception?($!)
101
+
102
+ puts "Problems loading #{options[:processor]}Processor: #{$!}"
103
+ end
104
+ end unless parent_options[:processor] # Don't let child override processor
105
+ end
106
+
107
+ def load_related_exception?(e) #:nodoc: implementation specific
108
+ case
109
+ when e.kind_of?(LoadError), e.kind_of?(MissingSourceFile), $!.class.name == "CompilationError"
110
+ # We can't rescue CompilationError directly, as it is part of the RubyInline library.
111
+ # We must instead rescue RuntimeError, and check the class' name.
112
+ true
113
+ else
114
+ false
115
+ end
116
+ end
117
+ private :load_related_exception?
118
+ end
119
+
120
+ module ClassMethods
121
+ delegate :content_types, :to => Technoweenie::AttachmentFu
122
+
123
+ # Performs common validations for attachment models.
124
+ def validates_as_attachment
125
+ validates_presence_of :size, :content_type, :filename
126
+ validate :attachment_attributes_valid?
127
+ end
128
+
129
+ # Returns true or false if the given content type is recognized as an image.
130
+ def image?(content_type)
131
+ content_types.include?(content_type)
132
+ end
133
+
134
+ def self.extended(base)
135
+ base.class_inheritable_accessor :attachment_options
136
+ base.before_destroy :destroy_thumbnails
137
+ base.before_validation :set_size_from_temp_path
138
+ base.after_save :after_process_attachment
139
+ base.after_destroy :destroy_file
140
+ base.after_validation :process_attachment
141
+ if defined?(::ActiveSupport::Callbacks)
142
+ base.define_callbacks :after_resize, :after_attachment_saved, :before_thumbnail_saved
143
+ end
144
+ end
145
+
146
+ unless defined?(::ActiveSupport::Callbacks)
147
+ # Callback after an image has been resized.
148
+ #
149
+ # class Foo < ActiveRecord::Base
150
+ # acts_as_attachment
151
+ # after_resize do |record, img|
152
+ # record.aspect_ratio = img.columns.to_f / img.rows.to_f
153
+ # end
154
+ # end
155
+ def after_resize(&block)
156
+ write_inheritable_array(:after_resize, [block])
157
+ end
158
+
159
+ # Callback after an attachment has been saved either to the file system or the DB.
160
+ # Only called if the file has been changed, not necessarily if the record is updated.
161
+ #
162
+ # class Foo < ActiveRecord::Base
163
+ # acts_as_attachment
164
+ # after_attachment_saved do |record|
165
+ # ...
166
+ # end
167
+ # end
168
+ def after_attachment_saved(&block)
169
+ write_inheritable_array(:after_attachment_saved, [block])
170
+ end
171
+
172
+ # Callback before a thumbnail is saved. Use this to pass any necessary extra attributes that may be required.
173
+ #
174
+ # class Foo < ActiveRecord::Base
175
+ # acts_as_attachment
176
+ # before_thumbnail_saved do |thumbnail|
177
+ # record = thumbnail.parent
178
+ # ...
179
+ # end
180
+ # end
181
+ def before_thumbnail_saved(&block)
182
+ write_inheritable_array(:before_thumbnail_saved, [block])
183
+ end
184
+ end
185
+
186
+ # Get the thumbnail class, which is the current attachment class by default.
187
+ # Configure this with the :thumbnail_class option.
188
+ def thumbnail_class
189
+ attachment_options[:thumbnail_class] = attachment_options[:thumbnail_class].constantize unless attachment_options[:thumbnail_class].is_a?(Class)
190
+ attachment_options[:thumbnail_class]
191
+ end
192
+
193
+ # Copies the given file path to a new tempfile, returning the closed tempfile.
194
+ def copy_to_temp_file(file, temp_base_name)
195
+ returning Tempfile.new(temp_base_name, Technoweenie::AttachmentFu.tempfile_path) do |tmp|
196
+ tmp.close
197
+ FileUtils.cp file, tmp.path
198
+ end
199
+ end
200
+
201
+ # Writes the given data to a new tempfile, returning the closed tempfile.
202
+ def write_to_temp_file(data, temp_base_name)
203
+ returning Tempfile.new(temp_base_name, Technoweenie::AttachmentFu.tempfile_path) do |tmp|
204
+ tmp.binmode
205
+ tmp.write data
206
+ tmp.close
207
+ end
208
+ end
209
+ end
210
+
211
+ module InstanceMethods
212
+ def self.included(base)
213
+ base.define_callbacks *[:after_resize, :after_attachment_saved, :before_thumbnail_saved] if base.respond_to?(:define_callbacks)
214
+ end
215
+
216
+ # Checks whether the attachment's content type is an image content type
217
+ def image?
218
+ self.class.image?(content_type)
219
+ end
220
+
221
+ # Returns true/false if an attachment is thumbnailable. A thumbnailable attachment has an image content type and the parent_id attribute.
222
+ def thumbnailable?
223
+ image? && respond_to?(:parent_id) && parent_id.nil?
224
+ end
225
+
226
+ # Returns the class used to create new thumbnails for this attachment.
227
+ def thumbnail_class
228
+ self.class.thumbnail_class
229
+ end
230
+
231
+ # Gets the thumbnail name for a filename. 'foo.jpg' becomes 'foo_thumbnail.jpg'
232
+ def thumbnail_name_for(thumbnail = nil)
233
+ return filename if thumbnail.blank?
234
+ ext = nil
235
+ basename = filename.gsub /\.\w+$/ do |s|
236
+ ext = s; ''
237
+ end
238
+ # ImageScience doesn't create gif thumbnails, only pngs
239
+ ext.sub!(/gif$/, 'png') if attachment_options[:processor] == "ImageScience"
240
+ "#{basename}_#{thumbnail}#{ext}"
241
+ end
242
+
243
+ # Creates or updates the thumbnail for the current attachment.
244
+ def create_or_update_thumbnail(temp_file, file_name_suffix, *size)
245
+ thumbnailable? || raise(ThumbnailError.new("Can't create a thumbnail if the content type is not an image or there is no parent_id column"))
246
+ returning find_or_initialize_thumbnail(file_name_suffix) do |thumb|
247
+ thumb.attributes = {
248
+ :content_type => content_type,
249
+ :filename => thumbnail_name_for(file_name_suffix),
250
+ :temp_path => temp_file,
251
+ :thumbnail_resize_options => size
252
+ }
253
+ callback_with_args :before_thumbnail_saved, thumb
254
+ thumb.save!
255
+ end
256
+ end
257
+
258
+ # Sets the content type.
259
+ def content_type=(new_type)
260
+ write_attribute :content_type, new_type.to_s.strip
261
+ end
262
+
263
+ # Sanitizes a filename.
264
+ def filename=(new_name)
265
+ write_attribute :filename, sanitize_filename(new_name)
266
+ end
267
+
268
+ # Returns the width/height in a suitable format for the image_tag helper: (100x100)
269
+ def image_size
270
+ [width.to_s, height.to_s] * 'x'
271
+ end
272
+
273
+ # Returns true if the attachment data will be written to the storage system on the next save
274
+ def save_attachment?
275
+ File.file?(temp_path.to_s)
276
+ end
277
+
278
+ # nil placeholder in case this field is used in a form.
279
+ def uploaded_data() nil; end
280
+
281
+ # This method handles the uploaded file object. If you set the field name to uploaded_data, you don't need
282
+ # any special code in your controller.
283
+ #
284
+ # <% form_for :attachment, :html => { :multipart => true } do |f| -%>
285
+ # <p><%= f.file_field :uploaded_data %></p>
286
+ # <p><%= submit_tag :Save %>
287
+ # <% end -%>
288
+ #
289
+ # @attachment = Attachment.create! params[:attachment]
290
+ #
291
+ # TODO: Allow it to work with Merb tempfiles too.
292
+ def uploaded_data=(file_data)
293
+ if file_data.respond_to?(:content_type)
294
+ return nil if file_data.size == 0
295
+ self.content_type = file_data.content_type
296
+ self.filename = file_data.original_filename if respond_to?(:filename)
297
+ else
298
+ return nil if file_data.blank? || file_data['size'] == 0
299
+ self.content_type = file_data['content_type']
300
+ self.filename = file_data['filename']
301
+ file_data = file_data['tempfile']
302
+ end
303
+ if file_data.is_a?(StringIO)
304
+ file_data.rewind
305
+ self.temp_data = file_data.read
306
+ else
307
+ self.temp_path = file_data
308
+ end
309
+ end
310
+
311
+ # Gets the latest temp path from the collection of temp paths. While working with an attachment,
312
+ # multiple Tempfile objects may be created for various processing purposes (resizing, for example).
313
+ # An array of all the tempfile objects is stored so that the Tempfile instance is held on to until
314
+ # it's not needed anymore. The collection is cleared after saving the attachment.
315
+ def temp_path
316
+ p = temp_paths.first
317
+ p.respond_to?(:path) ? p.path : p.to_s
318
+ end
319
+
320
+ # Gets an array of the currently used temp paths. Defaults to a copy of #full_filename.
321
+ def temp_paths
322
+ @temp_paths ||= (new_record? || !respond_to?(:full_filename) || !File.exist?(full_filename) ?
323
+ [] : [copy_to_temp_file(full_filename)])
324
+ end
325
+
326
+ # Adds a new temp_path to the array. This should take a string or a Tempfile. This class makes no
327
+ # attempt to remove the files, so Tempfiles should be used. Tempfiles remove themselves when they go out of scope.
328
+ # You can also use string paths for temporary files, such as those used for uploaded files in a web server.
329
+ def temp_path=(value)
330
+ temp_paths.unshift value
331
+ temp_path
332
+ end
333
+
334
+ # Gets the data from the latest temp file. This will read the file into memory.
335
+ def temp_data
336
+ save_attachment? ? File.read(temp_path) : nil
337
+ end
338
+
339
+ # Writes the given data to a Tempfile and adds it to the collection of temp files.
340
+ def temp_data=(data)
341
+ self.temp_path = write_to_temp_file data unless data.nil?
342
+ end
343
+
344
+ # Copies the given file to a randomly named Tempfile.
345
+ def copy_to_temp_file(file)
346
+ self.class.copy_to_temp_file file, random_tempfile_filename
347
+ end
348
+
349
+ # Writes the given file to a randomly named Tempfile.
350
+ def write_to_temp_file(data)
351
+ self.class.write_to_temp_file data, random_tempfile_filename
352
+ end
353
+
354
+ # Stub for creating a temp file from the attachment data. This should be defined in the backend module.
355
+ def create_temp_file() end
356
+
357
+ # Allows you to work with a processed representation (RMagick, ImageScience, etc) of the attachment in a block.
358
+ #
359
+ # @attachment.with_image do |img|
360
+ # self.data = img.thumbnail(100, 100).to_blob
361
+ # end
362
+ #
363
+ def with_image(&block)
364
+ self.class.with_image(temp_path, &block)
365
+ end
366
+
367
+ protected
368
+ # Generates a unique filename for a Tempfile.
369
+ def random_tempfile_filename
370
+ "#{rand Time.now.to_i}#{filename || 'attachment'}"
371
+ end
372
+
373
+ def sanitize_filename(filename)
374
+ return unless filename
375
+ returning filename.strip do |name|
376
+ # NOTE: File.basename doesn't work right with Windows paths on Unix
377
+ # get only the filename, not the whole path
378
+ name.gsub! /^.*(\\|\/)/, ''
379
+
380
+ # Finally, replace all non alphanumeric, underscore or periods with underscore
381
+ name.gsub! /[^A-Za-z0-9\.\-]/, '_'
382
+ end
383
+ end
384
+
385
+ # before_validation callback.
386
+ def set_size_from_temp_path
387
+ self.size = File.size(temp_path) if save_attachment?
388
+ end
389
+
390
+ # validates the size and content_type attributes according to the current model's options
391
+ def attachment_attributes_valid?
392
+ [:size, :content_type].each do |attr_name|
393
+ enum = attachment_options[attr_name]
394
+ errors.add attr_name, ActiveRecord::Errors.default_error_messages[:inclusion] unless enum.nil? || enum.include?(send(attr_name))
395
+ end
396
+ end
397
+
398
+ # Initializes a new thumbnail with the given suffix.
399
+ def find_or_initialize_thumbnail(file_name_suffix)
400
+ respond_to?(:parent_id) ?
401
+ thumbnail_class.find_or_initialize_by_thumbnail_and_parent_id(file_name_suffix.to_s, id) :
402
+ thumbnail_class.find_or_initialize_by_thumbnail(file_name_suffix.to_s)
403
+ end
404
+
405
+ # Stub for a #process_attachment method in a processor
406
+ def process_attachment
407
+ @saved_attachment = save_attachment?
408
+ end
409
+
410
+ # Cleans up after processing. Thumbnails are created, the attachment is stored to the backend, and the temp_paths are cleared.
411
+ def after_process_attachment
412
+ if @saved_attachment
413
+ if respond_to?(:process_attachment_with_processing) && thumbnailable? && !attachment_options[:thumbnails].blank? && parent_id.nil?
414
+ temp_file = temp_path || create_temp_file
415
+ attachment_options[:thumbnails].each { |suffix, size| create_or_update_thumbnail(temp_file, suffix, *size) }
416
+ end
417
+ save_to_storage
418
+ @temp_paths.clear
419
+ @saved_attachment = nil
420
+ callback :after_attachment_saved
421
+ end
422
+ end
423
+
424
+ # Resizes the given processed img object with either the attachment resize options or the thumbnail resize options.
425
+ def resize_image_or_thumbnail!(img)
426
+ if (!respond_to?(:parent_id) || parent_id.nil?) && attachment_options[:resize_to] # parent image
427
+ resize_image(img, attachment_options[:resize_to])
428
+ elsif thumbnail_resize_options # thumbnail
429
+ resize_image(img, thumbnail_resize_options)
430
+ end
431
+ end
432
+
433
+ # Yanked from ActiveRecord::Callbacks, modified so I can pass args to the callbacks besides self.
434
+ # Only accept blocks, however
435
+ if ActiveSupport.const_defined?(:Callbacks)
436
+ # Rails 2.1 and beyond!
437
+ def callback_with_args(method, arg = self)
438
+ notify(method)
439
+
440
+ result = run_callbacks(method, { :object => arg }) { |result, object| result == false }
441
+
442
+ if result != false && respond_to_without_attributes?(method)
443
+ result = send(method)
444
+ end
445
+
446
+ result
447
+ end
448
+
449
+ def run_callbacks(kind, options = {}, &block)
450
+ options.reverse_merge!( :object => self )
451
+ self.class.send("#{kind}_callback_chain").run(options[:object], options, &block)
452
+ end
453
+ else
454
+ # Rails 2.0
455
+ def callback_with_args(method, arg = self)
456
+ notify(method)
457
+
458
+ result = nil
459
+ callbacks_for(method).each do |callback|
460
+ result = callback.call(self, arg)
461
+ return false if result == false
462
+ end
463
+ result
464
+ end
465
+ end
466
+
467
+ # Removes the thumbnails for the attachment, if it has any
468
+ def destroy_thumbnails
469
+ self.thumbnails.each { |thumbnail| thumbnail.destroy } if thumbnailable?
470
+ end
471
+ end
472
+ end
473
+ end
@@ -0,0 +1,16 @@
1
+ require File.expand_path(File.join(File.dirname(__FILE__), '..', 'test_helper'))
2
+
3
+ class DbFileTest < Test::Unit::TestCase
4
+ include BaseAttachmentTests
5
+ attachment_model Attachment
6
+
7
+ def test_should_call_after_attachment_saved(klass = Attachment)
8
+ attachment_model.saves = 0
9
+ assert_created do
10
+ upload_file :filename => '/files/rails.png'
11
+ end
12
+ assert_equal 1, attachment_model.saves
13
+ end
14
+
15
+ test_against_subclass :test_should_call_after_attachment_saved, Attachment
16
+ end
@@ -0,0 +1,80 @@
1
+ require File.expand_path(File.join(File.dirname(__FILE__), '..', 'test_helper'))
2
+
3
+ class FileSystemTest < Test::Unit::TestCase
4
+ include BaseAttachmentTests
5
+ attachment_model FileAttachment
6
+
7
+ def test_filesystem_size_for_file_attachment(klass = FileAttachment)
8
+ attachment_model klass
9
+ assert_created 1 do
10
+ attachment = upload_file :filename => '/files/rails.png'
11
+ assert_equal attachment.size, File.open(attachment.full_filename).stat.size
12
+ end
13
+ end
14
+
15
+ test_against_subclass :test_filesystem_size_for_file_attachment, FileAttachment
16
+
17
+ def test_should_not_overwrite_file_attachment(klass = FileAttachment)
18
+ attachment_model klass
19
+ assert_created 2 do
20
+ real = upload_file :filename => '/files/rails.png'
21
+ assert_valid real
22
+ assert !real.new_record?, real.errors.full_messages.join("\n")
23
+ assert !real.size.zero?
24
+
25
+ fake = upload_file :filename => '/files/fake/rails.png'
26
+ assert_valid fake
27
+ assert !fake.size.zero?
28
+
29
+ assert_not_equal File.open(real.full_filename).stat.size, File.open(fake.full_filename).stat.size
30
+ end
31
+ end
32
+
33
+ test_against_subclass :test_should_not_overwrite_file_attachment, FileAttachment
34
+
35
+ def test_should_store_file_attachment_in_filesystem(klass = FileAttachment)
36
+ attachment_model klass
37
+ attachment = nil
38
+ assert_created do
39
+ attachment = upload_file :filename => '/files/rails.png'
40
+ assert_valid attachment
41
+ assert File.exists?(attachment.full_filename), "#{attachment.full_filename} does not exist"
42
+ end
43
+ attachment
44
+ end
45
+
46
+ test_against_subclass :test_should_store_file_attachment_in_filesystem, FileAttachment
47
+
48
+ def test_should_delete_old_file_when_updating(klass = FileAttachment)
49
+ attachment_model klass
50
+ attachment = upload_file :filename => '/files/rails.png'
51
+ old_filename = attachment.full_filename
52
+ assert_not_created do
53
+ use_temp_file 'files/rails.png' do |file|
54
+ attachment.filename = 'rails2.png'
55
+ attachment.temp_path = File.join(fixture_path, file)
56
+ attachment.save!
57
+ assert File.exists?(attachment.full_filename), "#{attachment.full_filename} does not exist"
58
+ assert !File.exists?(old_filename), "#{old_filename} still exists"
59
+ end
60
+ end
61
+ end
62
+
63
+ test_against_subclass :test_should_delete_old_file_when_updating, FileAttachment
64
+
65
+ def test_should_delete_old_file_when_renaming(klass = FileAttachment)
66
+ attachment_model klass
67
+ attachment = upload_file :filename => '/files/rails.png'
68
+ old_filename = attachment.full_filename
69
+ assert_not_created do
70
+ attachment.filename = 'rails2.png'
71
+ attachment.save
72
+ assert File.exists?(attachment.full_filename), "#{attachment.full_filename} does not exist"
73
+ assert !File.exists?(old_filename), "#{old_filename} still exists"
74
+ assert !attachment.reload.size.zero?
75
+ assert_equal 'rails2.png', attachment.filename
76
+ end
77
+ end
78
+
79
+ test_against_subclass :test_should_delete_old_file_when_renaming, FileAttachment
80
+ end
@@ -0,0 +1,119 @@
1
+ require File.expand_path(File.join(File.dirname(__FILE__), '..', '..', 'test_helper'))
2
+ require 'net/http'
3
+
4
+ class S3Test < Test::Unit::TestCase
5
+ def self.test_S3?
6
+ true unless ENV["TEST_S3"] == "false"
7
+ end
8
+
9
+ if test_S3? && File.exist?(File.join(File.dirname(__FILE__), '../../amazon_s3.yml'))
10
+ include BaseAttachmentTests
11
+ attachment_model S3Attachment
12
+
13
+ def test_should_create_correct_bucket_name(klass = S3Attachment)
14
+ attachment_model klass
15
+ attachment = upload_file :filename => '/files/rails.png'
16
+ assert_equal attachment.s3_config[:bucket_name], attachment.bucket_name
17
+ end
18
+
19
+ test_against_subclass :test_should_create_correct_bucket_name, S3Attachment
20
+
21
+ def test_should_create_default_path_prefix(klass = S3Attachment)
22
+ attachment_model klass
23
+ attachment = upload_file :filename => '/files/rails.png'
24
+ assert_equal File.join(attachment_model.table_name, attachment.attachment_path_id), attachment.base_path
25
+ end
26
+
27
+ test_against_subclass :test_should_create_default_path_prefix, S3Attachment
28
+
29
+ def test_should_create_custom_path_prefix(klass = S3WithPathPrefixAttachment)
30
+ attachment_model klass
31
+ attachment = upload_file :filename => '/files/rails.png'
32
+ assert_equal File.join('some/custom/path/prefix', attachment.attachment_path_id), attachment.base_path
33
+ end
34
+
35
+ test_against_subclass :test_should_create_custom_path_prefix, S3WithPathPrefixAttachment
36
+
37
+ def test_should_create_valid_url(klass = S3Attachment)
38
+ attachment_model klass
39
+ attachment = upload_file :filename => '/files/rails.png'
40
+ assert_equal "#{s3_protocol}#{s3_hostname}#{s3_port_string}/#{attachment.bucket_name}/#{attachment.full_filename}", attachment.s3_url
41
+ end
42
+
43
+ test_against_subclass :test_should_create_valid_url, S3Attachment
44
+
45
+ def test_should_create_authenticated_url(klass = S3Attachment)
46
+ attachment_model klass
47
+ attachment = upload_file :filename => '/files/rails.png'
48
+ assert_match /^http.+AWSAccessKeyId.+Expires.+Signature.+/, attachment.authenticated_s3_url(:use_ssl => true)
49
+ end
50
+
51
+ test_against_subclass :test_should_create_authenticated_url, S3Attachment
52
+
53
+ def test_should_create_authenticated_url_for_thumbnail(klass = S3Attachment)
54
+ attachment_model klass
55
+ attachment = upload_file :filename => '/files/rails.png'
56
+ ['large', :large].each do |thumbnail|
57
+ assert_match(
58
+ /^http.+rails_large\.png.+AWSAccessKeyId.+Expires.+Signature/,
59
+ attachment.authenticated_s3_url(thumbnail),
60
+ "authenticated_s3_url failed with #{thumbnail.class} parameter"
61
+ )
62
+ end
63
+ end
64
+
65
+ def test_should_save_attachment(klass = S3Attachment)
66
+ attachment_model klass
67
+ assert_created do
68
+ attachment = upload_file :filename => '/files/rails.png'
69
+ assert_valid attachment
70
+ assert attachment.image?
71
+ assert !attachment.size.zero?
72
+ assert_kind_of Net::HTTPOK, http_response_for(attachment.s3_url)
73
+ end
74
+ end
75
+
76
+ test_against_subclass :test_should_save_attachment, S3Attachment
77
+
78
+ def test_should_delete_attachment_from_s3_when_attachment_record_destroyed(klass = S3Attachment)
79
+ attachment_model klass
80
+ attachment = upload_file :filename => '/files/rails.png'
81
+
82
+ urls = [attachment.s3_url] + attachment.thumbnails.collect(&:s3_url)
83
+
84
+ urls.each {|url| assert_kind_of Net::HTTPOK, http_response_for(url) }
85
+ attachment.destroy
86
+ urls.each do |url|
87
+ begin
88
+ http_response_for(url)
89
+ rescue Net::HTTPForbidden, Net::HTTPNotFound
90
+ nil
91
+ end
92
+ end
93
+ end
94
+
95
+ test_against_subclass :test_should_delete_attachment_from_s3_when_attachment_record_destroyed, S3Attachment
96
+
97
+ protected
98
+ def http_response_for(url)
99
+ url = URI.parse(url)
100
+ Net::HTTP.start(url.host, url.port) {|http| http.request_head(url.path) }
101
+ end
102
+
103
+ def s3_protocol
104
+ Technoweenie::AttachmentFu::Backends::S3Backend.protocol
105
+ end
106
+
107
+ def s3_hostname
108
+ Technoweenie::AttachmentFu::Backends::S3Backend.hostname
109
+ end
110
+
111
+ def s3_port_string
112
+ Technoweenie::AttachmentFu::Backends::S3Backend.port_string
113
+ end
114
+ else
115
+ def test_flunk_s3
116
+ puts "s3 config file not loaded, tests not running"
117
+ end
118
+ end
119
+ end