pothoven-attachment_fu 3.2.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (49) hide show
  1. data/CHANGELOG +59 -0
  2. data/LICENSE +20 -0
  3. data/README +253 -0
  4. data/Rakefile +22 -0
  5. data/amazon_s3.yml.tpl +17 -0
  6. data/install.rb +7 -0
  7. data/lib/geometry.rb +96 -0
  8. data/lib/pothoven-attachment_fu.rb +21 -0
  9. data/lib/technoweenie/attachment_fu/backends/cloud_file_backend.rb +211 -0
  10. data/lib/technoweenie/attachment_fu/backends/db_file_backend.rb +39 -0
  11. data/lib/technoweenie/attachment_fu/backends/file_system_backend.rb +126 -0
  12. data/lib/technoweenie/attachment_fu/backends/s3_backend.rb +394 -0
  13. data/lib/technoweenie/attachment_fu/processors/core_image_processor.rb +66 -0
  14. data/lib/technoweenie/attachment_fu/processors/gd2_processor.rb +59 -0
  15. data/lib/technoweenie/attachment_fu/processors/image_science_processor.rb +80 -0
  16. data/lib/technoweenie/attachment_fu/processors/mini_magick_processor.rb +142 -0
  17. data/lib/technoweenie/attachment_fu/processors/rmagick_processor.rb +84 -0
  18. data/lib/technoweenie/attachment_fu.rb +577 -0
  19. data/rackspace_cloudfiles.yml.tpl +14 -0
  20. data/test/backends/db_file_test.rb +16 -0
  21. data/test/backends/file_system_test.rb +143 -0
  22. data/test/backends/remote/cloudfiles_test.rb +102 -0
  23. data/test/backends/remote/s3_test.rb +119 -0
  24. data/test/base_attachment_tests.rb +77 -0
  25. data/test/basic_test.rb +120 -0
  26. data/test/database.yml +18 -0
  27. data/test/extra_attachment_test.rb +67 -0
  28. data/test/fixtures/attachment.rb +304 -0
  29. data/test/fixtures/files/fake/rails.png +0 -0
  30. data/test/fixtures/files/foo.txt +1 -0
  31. data/test/fixtures/files/rails.jpg +0 -0
  32. data/test/fixtures/files/rails.png +0 -0
  33. data/test/geometry_test.rb +114 -0
  34. data/test/processors/core_image_test.rb +58 -0
  35. data/test/processors/gd2_test.rb +51 -0
  36. data/test/processors/image_science_test.rb +54 -0
  37. data/test/processors/mini_magick_test.rb +122 -0
  38. data/test/processors/rmagick_test.rb +272 -0
  39. data/test/schema.rb +136 -0
  40. data/test/test_helper.rb +180 -0
  41. data/test/validation_test.rb +55 -0
  42. data/vendor/red_artisan/core_image/filters/color.rb +27 -0
  43. data/vendor/red_artisan/core_image/filters/effects.rb +31 -0
  44. data/vendor/red_artisan/core_image/filters/perspective.rb +25 -0
  45. data/vendor/red_artisan/core_image/filters/quality.rb +25 -0
  46. data/vendor/red_artisan/core_image/filters/scale.rb +47 -0
  47. data/vendor/red_artisan/core_image/filters/watermark.rb +32 -0
  48. data/vendor/red_artisan/core_image/processor.rb +123 -0
  49. metadata +97 -0
@@ -0,0 +1,577 @@
1
+ module Technoweenie # :nodoc:
2
+ module AttachmentFu # :nodoc:
3
+ @@default_processors = %w(ImageScience Rmagick MiniMagick Gd2 CoreImage)
4
+ @@tempfile_path = Rails.root.join( 'tmp', 'attachment_fu')
5
+ @@content_types = [
6
+ 'image/jpeg',
7
+ 'image/pjpeg',
8
+ 'image/jpg',
9
+ 'image/gif',
10
+ 'image/png',
11
+ 'image/x-png',
12
+ 'image/jpg',
13
+ 'image/x-ms-bmp',
14
+ 'image/bmp',
15
+ 'image/x-bmp',
16
+ 'image/x-bitmap',
17
+ 'image/x-xbitmap',
18
+ 'image/x-win-bitmap',
19
+ 'image/x-windows-bmp',
20
+ 'image/ms-bmp',
21
+ 'application/bmp',
22
+ 'application/x-bmp',
23
+ 'application/x-win-bitmap',
24
+ 'application/preview',
25
+ 'image/jp_',
26
+ 'application/jpg',
27
+ 'application/x-jpg',
28
+ 'image/pipeg',
29
+ 'image/vnd.swiftview-jpeg',
30
+ 'image/x-xbitmap',
31
+ 'application/png',
32
+ 'application/x-png',
33
+ 'image/gi_',
34
+ 'image/x-citrix-pjpeg'
35
+ ]
36
+ mattr_reader :content_types, :tempfile_path, :default_processors
37
+ mattr_writer :tempfile_path
38
+
39
+ class ThumbnailError < StandardError; end
40
+ class AttachmentError < StandardError; end
41
+
42
+ module ActMethods
43
+ # Options:
44
+ # * <tt>:content_type</tt> - Allowed content types. Allows all by default. Use :image to allow all standard image types.
45
+ # * <tt>:min_size</tt> - Minimum size allowed. 1 byte is the default.
46
+ # * <tt>:max_size</tt> - Maximum size allowed. 1.megabyte is the default.
47
+ # * <tt>:size</tt> - Range of sizes allowed. (1..1.megabyte) is the default. This overrides the :min_size and :max_size options.
48
+ # * <tt>:resize_to</tt> - Used by RMagick to resize images. Pass either an array of width/height, or a geometry string.
49
+ # * <tt>:jpeg_quality</tt> - Used to provide explicit JPEG quality for thumbnail/resize saves. Can have multiple formats:
50
+ # * Integer from 0 (basically crap) to 100 (basically lossless, fat files).
51
+ # * When relying on ImageScience, you can also use one of its +JPEG_xxx+ constants for predefined ratios/settings.
52
+ # * You can also use a Hash, with keys being either thumbnail symbols (I repeat: _symbols_) or surface boundaries.
53
+ # A surface boundary is a string starting with either '<' or '>=', followed by a number of pixels. This lets you
54
+ # specify per-thumbnail or per-general-thumbnail-"size" JPEG qualities. (which can be useful when you have a
55
+ # _lot_ of thumbnail options). Surface example: +{ '<2000' => 90, '>=2000' => 75 }+.
56
+ # Defaults vary depending on the processor (ImageScience: 100%, Rmagick/MiniMagick/Gd2: 75%,
57
+ # CoreImage: auto-adjust). Note that only tdd-image_science (available from GitHub) currently supports explicit JPEG quality;
58
+ # the default image_science currently forces 100%.
59
+ # * <tt>:thumbnails</tt> - Specifies a set of thumbnails to generate. This accepts a hash of filename suffixes and
60
+ # RMagick resizing options. If you have a polymorphic parent relationship, you can provide parent-type-specific
61
+ # thumbnail settings by using a pair with the type string as key and a Hash of thumbnail definitions as value.
62
+ # AttachmentFu automatically detects your first polymorphic +belongs_to+ relationship.
63
+ # * <tt>:thumbnail_class</tt> - Set what class to use for thumbnails. This attachment class is used by default.
64
+ # * <tt>:path_prefix</tt> - path to store the uploaded files. Uses public/#{table_name} by default for the filesystem, and just #{table_name}
65
+ # for the S3 backend. Setting this sets the :storage to :file_system.
66
+
67
+ # * <tt>:storage</tt> - Use :file_system to specify the attachment data is stored with the file system. Defaults to :db_system.
68
+ # * <tt>:cloundfront</tt> - Set to true if you are using S3 storage and want to serve the files through CloudFront. You will need to
69
+ # set a distribution domain in the amazon_s3.yml config file. Defaults to false
70
+ # * <tt>:bucket_key</tt> - Use this to specify a different bucket key other than :bucket_name in the amazon_s3.yml file. This allows you to use
71
+ # different buckets for different models. An example setting would be :image_bucket and the you would need to define the name of the corresponding
72
+ # bucket in the amazon_s3.yml file.
73
+
74
+ # * <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.
75
+ #
76
+ # Examples:
77
+ # has_attachment :max_size => 1.kilobyte
78
+ # has_attachment :size => 1.megabyte..2.megabytes
79
+ # has_attachment :content_type => 'application/pdf'
80
+ # has_attachment :content_type => ['application/pdf', 'application/msword', 'text/plain']
81
+ # has_attachment :content_type => :image, :resize_to => [50,50]
82
+ # has_attachment :content_type => ['application/pdf', :image], :resize_to => 'x50'
83
+ # has_attachment :thumbnails => { :thumb => [50, 50], :geometry => 'x50' }
84
+ # has_attachment :storage => :file_system, :path_prefix => 'public/files'
85
+ # has_attachment :storage => :file_system, :path_prefix => 'public/files',
86
+ # :content_type => :image, :resize_to => [50,50]
87
+ # has_attachment :storage => :file_system, :path_prefix => 'public/files',
88
+ # :thumbnails => { :thumb => [50, 50], :geometry => 'x50' }
89
+ # has_attachment :storage => :s3
90
+ def has_attachment(options = {})
91
+ # this allows you to redefine the acts' options for each subclass, however
92
+ options[:min_size] ||= 1
93
+ options[:max_size] ||= 1.megabyte
94
+ options[:size] ||= (options[:min_size]..options[:max_size])
95
+ options[:thumbnails] ||= {}
96
+ options[:thumbnail_class] ||= self
97
+ options[:s3_access] ||= :public_read
98
+ options[:cloudfront] ||= false
99
+ options[:content_type] = [options[:content_type]].flatten.collect! { |t| t == :image ? Technoweenie::AttachmentFu.content_types : t }.flatten unless options[:content_type].nil?
100
+
101
+ unless options[:thumbnails].is_a?(Hash)
102
+ raise ArgumentError, ":thumbnails option should be a hash: e.g. :thumbnails => { :foo => '50x50' }"
103
+ end
104
+
105
+ extend ClassMethods unless (class << self; included_modules; end).include?(ClassMethods)
106
+ include InstanceMethods unless included_modules.include?(InstanceMethods)
107
+
108
+ parent_options = attachment_options || {}
109
+ # doing these shenanigans so that #attachment_options is available to processors and backends
110
+ self.attachment_options = options
111
+
112
+ attr_accessor :thumbnail_resize_options
113
+
114
+ attachment_options[:storage] ||= (attachment_options[:file_system_path] || attachment_options[:path_prefix]) ? :file_system : :db_file
115
+ attachment_options[:storage] ||= parent_options[:storage]
116
+ attachment_options[:path_prefix] ||= attachment_options[:file_system_path]
117
+ if attachment_options[:path_prefix].nil?
118
+ attachment_options[:path_prefix] = case attachment_options[:storage]
119
+ when :s3 then table_name
120
+ when :cloud_files then table_name
121
+ else File.join("public", table_name)
122
+ end
123
+ end
124
+ attachment_options[:path_prefix] = attachment_options[:path_prefix][1..-1] if options[:path_prefix].first == '/'
125
+
126
+ association_options = { :foreign_key => 'parent_id' }
127
+ if attachment_options[:association_options]
128
+ association_options.merge!(attachment_options[:association_options])
129
+ end
130
+ with_options(association_options) do |m|
131
+ m.has_many :thumbnails, :class_name => "::#{attachment_options[:thumbnail_class]}"
132
+ m.belongs_to :parent, :class_name => "::#{base_class}" unless options[:thumbnails].empty?
133
+ end
134
+
135
+ storage_mod = Technoweenie::AttachmentFu::Backends.const_get("#{options[:storage].to_s.classify}Backend")
136
+ include storage_mod unless included_modules.include?(storage_mod)
137
+
138
+ case attachment_options[:processor]
139
+ when :none, nil
140
+ processors = Technoweenie::AttachmentFu.default_processors.dup
141
+ begin
142
+ if processors.any?
143
+ attachment_options[:processor] = processors.first
144
+ processor_mod = Technoweenie::AttachmentFu::Processors.const_get("#{attachment_options[:processor].to_s.classify}Processor")
145
+ include processor_mod unless included_modules.include?(processor_mod)
146
+ end
147
+ rescue Object, Exception
148
+ raise unless load_related_exception?($!)
149
+
150
+ processors.shift
151
+ retry
152
+ end
153
+ else
154
+ begin
155
+ processor_mod = Technoweenie::AttachmentFu::Processors.const_get("#{attachment_options[:processor].to_s.classify}Processor")
156
+ include processor_mod unless included_modules.include?(processor_mod)
157
+ rescue Object, Exception
158
+ raise unless load_related_exception?($!)
159
+
160
+ puts "Problems loading #{options[:processor]}Processor: #{$!}"
161
+ end
162
+ end unless parent_options[:processor] # Don't let child override processor
163
+ end
164
+
165
+ def load_related_exception?(e) #:nodoc: implementation specific
166
+ case
167
+ when e.kind_of?(LoadError), e.kind_of?(MissingSourceFile), $!.class.name == "CompilationError"
168
+ # We can't rescue CompilationError directly, as it is part of the RubyInline library.
169
+ # We must instead rescue RuntimeError, and check the class' name.
170
+ true
171
+ else
172
+ false
173
+ end
174
+ end
175
+ private :load_related_exception?
176
+ end
177
+
178
+ module ClassMethods
179
+ delegate :content_types, :to => Technoweenie::AttachmentFu
180
+
181
+ # Performs common validations for attachment models.
182
+ def validates_as_attachment
183
+ validates_presence_of :size, :content_type, :filename
184
+ validate :attachment_attributes_valid?
185
+ end
186
+
187
+ # Returns true or false if the given content type is recognized as an image.
188
+ def image?(content_type)
189
+ content_types.include?(content_type)
190
+ end
191
+
192
+ def self.extended(base)
193
+ base.class_attribute :attachment_options
194
+ base.before_destroy :destroy_thumbnails
195
+ base.before_validation :set_size_from_temp_path
196
+ base.after_save :after_process_attachment
197
+ base.after_destroy :destroy_file
198
+ base.after_validation :process_attachment
199
+ #if defined?(::ActiveSupport::Callbacks)
200
+ # base.define_callbacks :after_resize, :after_attachment_saved, :before_thumbnail_saved
201
+ #end
202
+ end
203
+
204
+ unless defined?(::ActiveSupport::Callbacks)
205
+ # Callback after an image has been resized.
206
+ #
207
+ # class Foo < ActiveRecord::Base
208
+ # acts_as_attachment
209
+ # after_resize do |record, img|
210
+ # record.aspect_ratio = img.columns.to_f / img.rows.to_f
211
+ # end
212
+ # end
213
+ def after_resize(&block)
214
+ write_inheritable_array(:after_resize, [block])
215
+ end
216
+
217
+ # Callback after an attachment has been saved either to the file system or the DB.
218
+ # Only called if the file has been changed, not necessarily if the record is updated.
219
+ #
220
+ # class Foo < ActiveRecord::Base
221
+ # acts_as_attachment
222
+ # after_attachment_saved do |record|
223
+ # ...
224
+ # end
225
+ # end
226
+ def after_attachment_saved(&block)
227
+ write_inheritable_array(:after_attachment_saved, [block])
228
+ end
229
+
230
+ # Callback before a thumbnail is saved. Use this to pass any necessary extra attributes that may be required.
231
+ #
232
+ # class Foo < ActiveRecord::Base
233
+ # acts_as_attachment
234
+ # before_thumbnail_saved do |thumbnail|
235
+ # record = thumbnail.parent
236
+ # ...
237
+ # end
238
+ # end
239
+ def before_thumbnail_saved(&block)
240
+ write_inheritable_array(:before_thumbnail_saved, [block])
241
+ end
242
+ end
243
+
244
+ # Get the thumbnail class, which is the current attachment class by default.
245
+ # Configure this with the :thumbnail_class option.
246
+ def thumbnail_class
247
+ attachment_options[:thumbnail_class] = attachment_options[:thumbnail_class].constantize unless attachment_options[:thumbnail_class].is_a?(Class)
248
+ attachment_options[:thumbnail_class]
249
+ end
250
+
251
+ # Copies the given file path to a new tempfile, returning the closed tempfile.
252
+ def copy_to_temp_file(file, temp_base_name)
253
+ Tempfile.new(temp_base_name, Technoweenie::AttachmentFu.tempfile_path).tap do |tmp|
254
+ tmp.close
255
+ FileUtils.cp file, tmp.path
256
+ end
257
+ end
258
+
259
+ # Writes the given data to a new tempfile, returning the closed tempfile.
260
+ def write_to_temp_file(data, temp_base_name)
261
+ Tempfile.new(temp_base_name, Technoweenie::AttachmentFu.tempfile_path).tap do |tmp|
262
+ tmp.binmode
263
+ tmp.write data
264
+ tmp.close
265
+ end
266
+ end
267
+
268
+ def polymorphic_relation_type_column
269
+ return @@_polymorphic_relation_type_column if defined?(@@_polymorphic_relation_type_column)
270
+ # Checked against ActiveRecord 1.15.6 through Edge @ 2009-08-05.
271
+ ref = reflections.values.detect { |r| r.macro == :belongs_to && r.options[:polymorphic] }
272
+ @@_polymorphic_relation_type_column = ref && ref.options[:foreign_type]
273
+ end
274
+ end
275
+
276
+ module InstanceMethods
277
+ def self.included(base)
278
+ base.define_callbacks *[:after_resize, :after_attachment_saved, :before_thumbnail_saved] if base.respond_to?(:define_callbacks)
279
+ end
280
+
281
+ # Checks whether the attachment's content type is an image content type
282
+ def image?
283
+ self.class.image?(content_type)
284
+ end
285
+
286
+ # Returns true/false if an attachment is thumbnailable. A thumbnailable attachment has an image content type and the parent_id attribute.
287
+ def thumbnailable?
288
+ image? && respond_to?(:parent_id) && parent_id.nil?
289
+ end
290
+
291
+ # Returns the class used to create new thumbnails for this attachment.
292
+ def thumbnail_class
293
+ self.class.thumbnail_class
294
+ end
295
+
296
+ # Gets the thumbnail name for a filename. 'foo.jpg' becomes 'foo_thumbnail.jpg'
297
+ def thumbnail_name_for(thumbnail = nil)
298
+ return filename if thumbnail.blank?
299
+ ext = nil
300
+ basename = filename.gsub /\.\w+$/ do |s|
301
+ ext = s; ''
302
+ end
303
+ # ImageScience doesn't create gif thumbnails, only pngs
304
+ ext.sub!(/gif$/i, 'png') if attachment_options[:processor] == "ImageScience"
305
+ "#{basename}_#{thumbnail}#{ext}"
306
+ end
307
+
308
+ # Creates or updates the thumbnail for the current attachment.
309
+ def create_or_update_thumbnail(temp_file, file_name_suffix, *size)
310
+ thumbnailable? || raise(ThumbnailError.new("Can't create a thumbnail if the content type is not an image or there is no parent_id column"))
311
+ find_or_initialize_thumbnail(file_name_suffix).tap do |thumb|
312
+ thumb.temp_paths.unshift temp_file
313
+ thumb.send(:assign_attributes, {
314
+ :content_type => content_type,
315
+ :filename => thumbnail_name_for(file_name_suffix),
316
+ :thumbnail_resize_options => size
317
+ }, :without_protection => true)
318
+ callback_with_args :before_thumbnail_saved, thumb
319
+ thumb.save!
320
+ end
321
+ end
322
+
323
+ # Sets the content type.
324
+ def content_type=(new_type)
325
+ write_attribute :content_type, new_type.to_s.strip
326
+ end
327
+
328
+ # Sanitizes a filename.
329
+ def filename=(new_name)
330
+ write_attribute :filename, sanitize_filename(new_name)
331
+ end
332
+
333
+ # Returns the width/height in a suitable format for the image_tag helper: (100x100)
334
+ def image_size
335
+ [width.to_s, height.to_s] * 'x'
336
+ end
337
+
338
+ # Returns true if the attachment data will be written to the storage system on the next save
339
+ def save_attachment?
340
+ File.file?(temp_path.class == String ? temp_path : temp_path.to_filename)
341
+ end
342
+
343
+ # nil placeholder in case this field is used in a form.
344
+ def uploaded_data() nil; end
345
+
346
+ # This method handles the uploaded file object. If you set the field name to uploaded_data, you don't need
347
+ # any special code in your controller.
348
+ #
349
+ # <% form_for :attachment, :html => { :multipart => true } do |f| -%>
350
+ # <p><%= f.file_field :uploaded_data %></p>
351
+ # <p><%= submit_tag :Save %>
352
+ # <% end -%>
353
+ #
354
+ # @attachment = Attachment.create! params[:attachment]
355
+ #
356
+ # TODO: Allow it to work with Merb tempfiles too.
357
+ def uploaded_data=(file_data)
358
+ if file_data.respond_to?(:content_type)
359
+ return nil if file_data.size == 0
360
+ self.content_type = file_data.content_type
361
+ self.filename = file_data.original_filename if respond_to?(:filename)
362
+ else
363
+ return nil if file_data.blank? || file_data['size'] == 0
364
+ self.content_type = file_data['content_type']
365
+ self.filename = file_data['filename']
366
+ file_data = file_data['tempfile']
367
+ end
368
+ if file_data.is_a?(StringIO)
369
+ file_data.rewind
370
+ set_temp_data file_data.read
371
+ else
372
+ file_data.respond_to?(:tempfile) ? self.temp_paths.unshift( file_data.tempfile.path ) : self.temp_paths.unshift( file_data.path )
373
+ end
374
+ end
375
+
376
+ # Gets the latest temp path from the collection of temp paths. While working with an attachment,
377
+ # multiple Tempfile objects may be created for various processing purposes (resizing, for example).
378
+ # An array of all the tempfile objects is stored so that the Tempfile instance is held on to until
379
+ # it's not needed anymore. The collection is cleared after saving the attachment.
380
+ def temp_path
381
+ p = temp_paths.first
382
+ p.respond_to?(:path) ? p.path : p.to_s
383
+ end
384
+
385
+ # Gets an array of the currently used temp paths. Defaults to a copy of #full_filename.
386
+ def temp_paths
387
+ @temp_paths ||= (new_record? || !respond_to?(:full_filename) || !File.exist?(full_filename) ?
388
+ [] : [copy_to_temp_file(full_filename)])
389
+ end
390
+
391
+ # Gets the data from the latest temp file. This will read the file into memory.
392
+ def temp_data
393
+ save_attachment? ? File.read(temp_path) : nil
394
+ end
395
+
396
+ # Writes the given data to a Tempfile and adds it to the collection of temp files.
397
+ def set_temp_data(data)
398
+ temp_paths.unshift write_to_temp_file data unless data.nil?
399
+ end
400
+
401
+ # Copies the given file to a randomly named Tempfile.
402
+ def copy_to_temp_file(file)
403
+ self.class.copy_to_temp_file file, random_tempfile_filename
404
+ end
405
+
406
+ # Writes the given file to a randomly named Tempfile.
407
+ def write_to_temp_file(data)
408
+ self.class.write_to_temp_file data, random_tempfile_filename
409
+ end
410
+
411
+ # Stub for creating a temp file from the attachment data. This should be defined in the backend module.
412
+ def create_temp_file() end
413
+
414
+ # Allows you to work with a processed representation (RMagick, ImageScience, etc) of the attachment in a block.
415
+ #
416
+ # @attachment.with_image do |img|
417
+ # self.data = img.thumbnail(100, 100).to_blob
418
+ # end
419
+ #
420
+ def with_image(&block)
421
+ self.class.with_image(temp_path, &block)
422
+ end
423
+
424
+ protected
425
+ # Generates a unique filename for a Tempfile.
426
+ def random_tempfile_filename
427
+ "#{rand Time.now.to_i}#{filename || 'attachment'}"
428
+ end
429
+
430
+ def sanitize_filename(filename)
431
+ return unless filename
432
+ filename.strip.tap do |name|
433
+ # NOTE: File.basename doesn't work right with Windows paths on Unix
434
+ # get only the filename, not the whole path
435
+ name.gsub! /^.*(\\|\/)/, ''
436
+
437
+ # Finally, replace all non alphanumeric, underscore or periods with underscore
438
+ name.gsub! /[^A-Za-z0-9\.\-]/, '_'
439
+ end
440
+ end
441
+
442
+ # before_validation callback.
443
+ def set_size_from_temp_path
444
+ self.size = File.size(temp_path) if save_attachment?
445
+ end
446
+
447
+ # validates the size and content_type attributes according to the current model's options
448
+ def attachment_attributes_valid?
449
+ [:size, :content_type].each do |attr_name|
450
+ enum = attachment_options[attr_name]
451
+ if Object.const_defined?(:I18n) # Rails >= 2.2
452
+ errors.add attr_name, I18n.translate("activerecord.errors.messages.inclusion", attr_name => enum) unless enum.nil? || enum.include?(send(attr_name))
453
+ else
454
+ errors.add attr_name, ActiveRecord::Errors.default_error_messages[:inclusion] unless enum.nil? || enum.include?(send(attr_name))
455
+ end
456
+ end
457
+ end
458
+
459
+ # Initializes a new thumbnail with the given suffix.
460
+ def find_or_initialize_thumbnail(file_name_suffix)
461
+ respond_to?(:parent_id) ?
462
+ thumbnail_class.find_or_initialize_by_thumbnail_and_parent_id(file_name_suffix.to_s, id) :
463
+ thumbnail_class.find_or_initialize_by_thumbnail(file_name_suffix.to_s)
464
+ end
465
+
466
+ # Stub for a #process_attachment method in a processor
467
+ def process_attachment
468
+ @saved_attachment = save_attachment?
469
+ end
470
+
471
+ # Cleans up after processing. Thumbnails are created, the attachment is stored to the backend, and the temp_paths are cleared.
472
+ def after_process_attachment
473
+ if @saved_attachment
474
+ if respond_to?(:process_attachment_with_processing) && thumbnailable? && !attachment_options[:thumbnails].blank? && parent_id.nil?
475
+ temp_file = temp_path || create_temp_file
476
+ attachment_options[:thumbnails].each { |suffix, size|
477
+ if size.is_a?(Symbol)
478
+ parent_type = polymorphic_parent_type
479
+ next unless parent_type && [parent_type, parent_type.tableize].include?(suffix.to_s) && respond_to?(size)
480
+ size = send(size)
481
+ end
482
+ if size.is_a?(Hash)
483
+ parent_type = polymorphic_parent_type
484
+ next unless parent_type && [parent_type, parent_type.tableize].include?(suffix.to_s)
485
+ size.each { |ppt_suffix, ppt_size|
486
+ create_or_update_thumbnail(temp_file, ppt_suffix, *ppt_size)
487
+ }
488
+ else
489
+ create_or_update_thumbnail(temp_file, suffix, *size)
490
+ end
491
+ }
492
+ end
493
+ save_to_storage
494
+ @temp_paths.clear
495
+ @saved_attachment = nil
496
+ #callback :after_attachment_saved
497
+ callback_with_args :after_attachment_saved, nil
498
+ end
499
+ end
500
+
501
+ # Resizes the given processed img object with either the attachment resize options or the thumbnail resize options.
502
+ def resize_image_or_thumbnail!(img)
503
+ if (!respond_to?(:parent_id) || parent_id.nil?) && attachment_options[:resize_to] # parent image
504
+ resize_image(img, attachment_options[:resize_to])
505
+ elsif thumbnail_resize_options # thumbnail
506
+ resize_image(img, thumbnail_resize_options)
507
+ end
508
+ end
509
+
510
+ if defined?(Rails) && Rails::VERSION::MAJOR >= 3
511
+ def callback_with_args(method, arg = self)
512
+ if respond_to?(method)
513
+ send(method, arg)
514
+ end
515
+ end
516
+ # Yanked from ActiveRecord::Callbacks, modified so I can pass args to the callbacks besides self.
517
+ # Only accept blocks, however
518
+ elsif ActiveSupport.const_defined?(:Callbacks)
519
+ # Rails 2.1 and beyond!
520
+ def callback_with_args(method, arg = self)
521
+ notify(method)
522
+
523
+ result = run_callbacks(method, { :object => arg }) { |result, object| result == false }
524
+
525
+ if result != false && respond_to_without_attributes?(method)
526
+ result = send(method)
527
+ end
528
+
529
+ result
530
+ end
531
+
532
+ def run_callbacks(kind, options = {}, &block)
533
+ options.reverse_merge!( :object => self )
534
+ self.class.send("#{kind}_callback_chain").run(options[:object], options, &block)
535
+ end
536
+ else
537
+ # Rails 2.0
538
+ def callback_with_args(method, arg = self)
539
+ notify(method)
540
+
541
+ result = nil
542
+ callbacks_for(method).each do |callback|
543
+ result = callback.call(self, arg)
544
+ return false if result == false
545
+ end
546
+ result
547
+ end
548
+ end
549
+
550
+ # Removes the thumbnails for the attachment, if it has any
551
+ def destroy_thumbnails
552
+ self.thumbnails.each { |thumbnail| thumbnail.destroy } if thumbnailable?
553
+ end
554
+
555
+ def polymorphic_parent_type
556
+ rel_name = self.class.polymorphic_relation_type_column
557
+ rel_name && send(rel_name)
558
+ end
559
+
560
+ def get_jpeg_quality(require_0_to_100 = true)
561
+ quality = attachment_options[:jpeg_quality]
562
+ if quality.is_a?(Hash)
563
+ sbl_quality = thumbnail && quality[thumbnail.to_sym]
564
+ sbl_quality = nil if sbl_quality && require_0_to_100 && !sbl_quality.to_i.between?(0, 100)
565
+ surface = (width || 1) * (height || 1)
566
+ size_quality = quality.detect { |k, v|
567
+ next unless k.is_a?(String) && k =~ /^(<|>=)(\d+)$/
568
+ op, threshold = $1, $2.to_i
569
+ surface.send(op, threshold)
570
+ }
571
+ quality = sbl_quality || size_quality && size_quality[1]
572
+ end
573
+ return quality && (!require_0_to_100 || quality.to_i.between?(0, 100)) ? quality : nil
574
+ end
575
+ end
576
+ end
577
+ end
@@ -0,0 +1,14 @@
1
+ development:
2
+ container_name: appname_development
3
+ username:
4
+ api_key:
5
+
6
+ test:
7
+ container_name: appname_test
8
+ username:
9
+ api_key:
10
+
11
+ production:
12
+ container_name: appname_production
13
+ username:
14
+ api_key:
@@ -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