miloops-attachment_fu 3.2.5

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