ioquatix-attachment_fu 1.0.1

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,59 @@
1
+ require 'red_artisan/core_image/processor'
2
+
3
+ module Technoweenie # :nodoc:
4
+ module AttachmentFu # :nodoc:
5
+ module Processors
6
+ module CoreImageProcessor
7
+ def self.included(base)
8
+ base.send :extend, ClassMethods
9
+ base.alias_method_chain :process_attachment, :processing
10
+ end
11
+
12
+ module ClassMethods
13
+ def with_image(file, &block)
14
+ block.call OSX::CIImage.from(file)
15
+ end
16
+ end
17
+
18
+ protected
19
+ def process_attachment_with_processing
20
+ return unless process_attachment_without_processing
21
+ with_image do |img|
22
+ self.width = img.extent.size.width if respond_to?(:width)
23
+ self.height = img.extent.size.height if respond_to?(:height)
24
+ resize_image_or_thumbnail! img
25
+ callback_with_args :after_resize, img
26
+ end if image?
27
+ end
28
+
29
+ # Performs the actual resizing operation for a thumbnail
30
+ def resize_image(img, size)
31
+ processor = ::RedArtisan::CoreImage::Processor.new(img)
32
+ size = size.first if size.is_a?(Array) && size.length == 1
33
+ if size.is_a?(Fixnum) || (size.is_a?(Array) && size.first.is_a?(Fixnum))
34
+ if size.is_a?(Fixnum)
35
+ processor.fit(size)
36
+ else
37
+ processor.resize(size[0], size[1])
38
+ end
39
+ else
40
+ new_size = [img.extent.size.width, img.extent.size.height] / size.to_s
41
+ processor.resize(new_size[0], new_size[1])
42
+ end
43
+
44
+ processor.render do |result|
45
+ self.width = result.extent.size.width if respond_to?(:width)
46
+ self.height = result.extent.size.height if respond_to?(:height)
47
+
48
+ # Get a new temp_path for the image before saving
49
+ temp_paths.unshift Tempfile.new(random_tempfile_filename, Technoweenie::AttachmentFu.tempfile_path).path
50
+ result.save self.temp_path, OSX::NSJPEGFileType
51
+ self.size = File.size(self.temp_path)
52
+ end
53
+ end
54
+ end
55
+ end
56
+ end
57
+ end
58
+
59
+
@@ -0,0 +1,54 @@
1
+ require 'rubygems'
2
+ require 'gd2'
3
+ module Technoweenie # :nodoc:
4
+ module AttachmentFu # :nodoc:
5
+ module Processors
6
+ module Gd2Processor
7
+ def self.included(base)
8
+ base.send :extend, ClassMethods
9
+ base.alias_method_chain :process_attachment, :processing
10
+ end
11
+
12
+ module ClassMethods
13
+ # Yields a block containing a GD2 Image for the given binary data.
14
+ def with_image(file, &block)
15
+ im = GD2::Image.import(file)
16
+ block.call(im)
17
+ end
18
+ end
19
+
20
+ protected
21
+ def process_attachment_with_processing
22
+ return unless process_attachment_without_processing && image?
23
+ with_image do |img|
24
+ resize_image_or_thumbnail! img
25
+ self.width = img.width
26
+ self.height = img.height
27
+ callback_with_args :after_resize, img
28
+ end
29
+ end
30
+
31
+ # Performs the actual resizing operation for a thumbnail
32
+ def resize_image(img, size)
33
+ size = size.first if size.is_a?(Array) && size.length == 1
34
+ if size.is_a?(Fixnum) || (size.is_a?(Array) && size.first.is_a?(Fixnum))
35
+ if size.is_a?(Fixnum)
36
+ # Borrowed from image science's #thumbnail method and adapted
37
+ # for this.
38
+ scale = size.to_f / (img.width > img.height ? img.width.to_f : img.height.to_f)
39
+ img.resize!((img.width * scale).round(1), (img.height * scale).round(1), false)
40
+ else
41
+ img.resize!(size.first, size.last, false)
42
+ end
43
+ else
44
+ w, h = [img.width, img.height] / size.to_s
45
+ img.resize!(w, h, false)
46
+ end
47
+ temp_paths.unshift random_tempfile_filename
48
+ self.size = img.export(self.temp_path)
49
+ end
50
+
51
+ end
52
+ end
53
+ end
54
+ end
@@ -0,0 +1,61 @@
1
+ require 'image_science'
2
+ module Technoweenie # :nodoc:
3
+ module AttachmentFu # :nodoc:
4
+ module Processors
5
+ module ImageScienceProcessor
6
+ def self.included(base)
7
+ base.send :extend, ClassMethods
8
+ base.alias_method_chain :process_attachment, :processing
9
+ end
10
+
11
+ module ClassMethods
12
+ # Yields a block containing an Image Science image for the given binary data.
13
+ def with_image(file, &block)
14
+ ::ImageScience.with_image file, &block
15
+ end
16
+ end
17
+
18
+ protected
19
+ def process_attachment_with_processing
20
+ return unless process_attachment_without_processing && image?
21
+ with_image do |img|
22
+ self.width = img.width if respond_to?(:width)
23
+ self.height = img.height if respond_to?(:height)
24
+ resize_image_or_thumbnail! img
25
+ end
26
+ end
27
+
28
+ # Performs the actual resizing operation for a thumbnail
29
+ def resize_image(img, size)
30
+ # create a dummy temp file to write to
31
+ # ImageScience doesn't handle all gifs properly, so it converts them to
32
+ # pngs for thumbnails. It has something to do with trying to save gifs
33
+ # with a larger palette than 256 colors, which is all the gif format
34
+ # supports.
35
+ filename.sub! /gif$/, 'png'
36
+ content_type.sub!(/gif$/, 'png')
37
+ temp_paths.unshift write_to_temp_file(filename)
38
+ grab_dimensions = lambda do |img|
39
+ self.width = img.width if respond_to?(:width)
40
+ self.height = img.height if respond_to?(:height)
41
+ img.save self.temp_path
42
+ self.size = File.size(self.temp_path)
43
+ callback_with_args :after_resize, img
44
+ end
45
+
46
+ size = size.first if size.is_a?(Array) && size.length == 1
47
+ if size.is_a?(Fixnum) || (size.is_a?(Array) && size.first.is_a?(Fixnum))
48
+ if size.is_a?(Fixnum)
49
+ img.thumbnail(size, &grab_dimensions)
50
+ else
51
+ img.resize(size[0], size[1], &grab_dimensions)
52
+ end
53
+ else
54
+ new_size = [img.width, img.height] / size.to_s
55
+ img.resize(new_size[0], new_size[1], &grab_dimensions)
56
+ end
57
+ end
58
+ end
59
+ end
60
+ end
61
+ end
@@ -0,0 +1,59 @@
1
+ require 'mini_magick'
2
+ module Technoweenie # :nodoc:
3
+ module AttachmentFu # :nodoc:
4
+ module Processors
5
+ module MiniMagickProcessor
6
+ def self.included(base)
7
+ base.send :extend, ClassMethods
8
+ base.alias_method_chain :process_attachment, :processing
9
+ end
10
+
11
+ module ClassMethods
12
+ # Yields a block containing an MiniMagick Image for the given binary data.
13
+ def with_image(file, &block)
14
+ begin
15
+ binary_data = file.is_a?(MiniMagick::Image) ? file : MiniMagick::Image.from_file(file) unless !Object.const_defined?(:MiniMagick)
16
+ rescue
17
+ # Log the failure to load the image.
18
+ logger.debug("Exception working with image: #{$!}")
19
+ binary_data = nil
20
+ end
21
+ block.call binary_data if block && binary_data
22
+ ensure
23
+ !binary_data.nil?
24
+ end
25
+ end
26
+
27
+ protected
28
+ def process_attachment_with_processing
29
+ return unless process_attachment_without_processing
30
+ with_image do |img|
31
+ resize_image_or_thumbnail! img
32
+ self.width = img[:width] if respond_to?(:width)
33
+ self.height = img[:height] if respond_to?(:height)
34
+ callback_with_args :after_resize, img
35
+ end if image?
36
+ end
37
+
38
+ # Performs the actual resizing operation for a thumbnail
39
+ def resize_image(img, size)
40
+ size = size.first if size.is_a?(Array) && size.length == 1
41
+ img.combine_options do |commands|
42
+ commands.strip unless attachment_options[:keep_profile]
43
+ if size.is_a?(Fixnum) || (size.is_a?(Array) && size.first.is_a?(Fixnum))
44
+ if size.is_a?(Fixnum)
45
+ size = [size, size]
46
+ commands.resize(size.join('x'))
47
+ else
48
+ commands.resize(size.join('x') + '!')
49
+ end
50
+ else
51
+ commands.resize(size.to_s)
52
+ end
53
+ end
54
+ temp_paths.unshift img
55
+ end
56
+ end
57
+ end
58
+ end
59
+ end
@@ -0,0 +1,54 @@
1
+ require 'RMagick'
2
+ module Technoweenie # :nodoc:
3
+ module AttachmentFu # :nodoc:
4
+ module Processors
5
+ module RmagickProcessor
6
+ def self.included(base)
7
+ base.send :extend, ClassMethods
8
+ base.alias_method_chain :process_attachment, :processing
9
+ end
10
+
11
+ module ClassMethods
12
+ # Yields a block containing an RMagick Image for the given binary data.
13
+ def with_image(file, &block)
14
+ begin
15
+ binary_data = file.is_a?(Magick::Image) ? file : Magick::Image.read(file).first unless !Object.const_defined?(:Magick)
16
+ rescue
17
+ # Log the failure to load the image. This should match ::Magick::ImageMagickError
18
+ # but that would cause acts_as_attachment to require rmagick.
19
+ logger.debug("Exception working with image: #{$!}")
20
+ binary_data = nil
21
+ end
22
+ block.call binary_data if block && binary_data
23
+ ensure
24
+ !binary_data.nil?
25
+ end
26
+ end
27
+
28
+ protected
29
+ def process_attachment_with_processing
30
+ return unless process_attachment_without_processing
31
+ with_image do |img|
32
+ resize_image_or_thumbnail! img
33
+ self.width = img.columns if respond_to?(:width)
34
+ self.height = img.rows if respond_to?(:height)
35
+ callback_with_args :after_resize, img
36
+ end if image?
37
+ end
38
+
39
+ # Performs the actual resizing operation for a thumbnail
40
+ def resize_image(img, size)
41
+ size = size.first if size.is_a?(Array) && size.length == 1 && !size.first.is_a?(Fixnum)
42
+ if size.is_a?(Fixnum) || (size.is_a?(Array) && size.first.is_a?(Fixnum))
43
+ size = [size, size] if size.is_a?(Fixnum)
44
+ img.thumbnail!(*size)
45
+ else
46
+ img.change_geometry(size.to_s) { |cols, rows, image| image.resize!(cols<1 ? 1 : cols, rows<1 ? 1 : rows) }
47
+ end
48
+ img.strip! unless attachment_options[:keep_profile]
49
+ temp_paths.unshift write_to_temp_file(img.to_blob)
50
+ end
51
+ end
52
+ end
53
+ end
54
+ end
@@ -0,0 +1,495 @@
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 = [
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
+ ]
35
+ mattr_reader :content_types, :tempfile_path, :default_processors
36
+ mattr_writer :tempfile_path
37
+
38
+ class ThumbnailError < StandardError; end
39
+ class AttachmentError < StandardError; end
40
+
41
+ module ActMethods
42
+ # Options:
43
+ # * <tt>:content_type</tt> - Allowed content types. Allows all by default. Use :image to allow all standard image types.
44
+ # * <tt>:min_size</tt> - Minimum size allowed. 1 byte is the default.
45
+ # * <tt>:max_size</tt> - Maximum size allowed. 1.megabyte is the default.
46
+ # * <tt>:size</tt> - Range of sizes allowed. (1..1.megabyte) is the default. This overrides the :min_size and :max_size options.
47
+ # * <tt>:resize_to</tt> - Used by RMagick to resize images. Pass either an array of width/height, or a geometry string.
48
+ # * <tt>:thumbnails</tt> - Specifies a set of thumbnails to generate. This accepts a hash of filename suffixes and RMagick resizing options.
49
+ # * <tt>:thumbnail_class</tt> - Set what class to use for thumbnails. This attachment class is used by default.
50
+ # * <tt>:path_prefix</tt> - path to store the uploaded files. Uses public/#{table_name} by default for the filesystem, and just #{table_name}
51
+ # for the S3 backend. Setting this sets the :storage to :file_system.
52
+ # * <tt>:storage</tt> - Use :file_system to specify the attachment data is stored with the file system. Defaults to :db_system.
53
+
54
+ # * <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.
55
+ #
56
+ # Examples:
57
+ # has_attachment :max_size => 1.kilobyte
58
+ # has_attachment :size => 1.megabyte..2.megabytes
59
+ # has_attachment :content_type => 'application/pdf'
60
+ # has_attachment :content_type => ['application/pdf', 'application/msword', 'text/plain']
61
+ # has_attachment :content_type => :image, :resize_to => [50,50]
62
+ # has_attachment :content_type => ['application/pdf', :image], :resize_to => 'x50'
63
+ # has_attachment :thumbnails => { :thumb => [50, 50], :geometry => 'x50' }
64
+ # has_attachment :storage => :file_system, :path_prefix => 'public/files'
65
+ # has_attachment :storage => :file_system, :path_prefix => 'public/files',
66
+ # :content_type => :image, :resize_to => [50,50]
67
+ # has_attachment :storage => :file_system, :path_prefix => 'public/files',
68
+ # :thumbnails => { :thumb => [50, 50], :geometry => 'x50' }
69
+ # has_attachment :storage => :s3
70
+ def has_attachment(options = {})
71
+ # this allows you to redefine the acts' options for each subclass, however
72
+ options[:min_size] ||= 1
73
+ options[:max_size] ||= 1.megabyte
74
+ options[:size] ||= (options[:min_size]..options[:max_size])
75
+ options[:thumbnails] ||= {}
76
+ options[:thumbnail_class] ||= self
77
+ options[:s3_access] ||= :public_read
78
+ options[:content_type] = [options[:content_type]].flatten.collect! { |t| t == :image ? Technoweenie::AttachmentFu.content_types : t }.flatten unless options[:content_type].nil?
79
+
80
+ unless options[:thumbnails].is_a?(Hash)
81
+ raise ArgumentError, ":thumbnails option should be a hash: e.g. :thumbnails => { :foo => '50x50' }"
82
+ end
83
+
84
+ extend ClassMethods unless (class << self; included_modules; end).include?(ClassMethods)
85
+ include InstanceMethods unless included_modules.include?(InstanceMethods)
86
+
87
+ parent_options = attachment_options || {}
88
+ # doing these shenanigans so that #attachment_options is available to processors and backends
89
+ self.attachment_options = options
90
+
91
+ attr_accessor :thumbnail_resize_options
92
+
93
+ attachment_options[:storage] ||= (attachment_options[:file_system_path] || attachment_options[:path_prefix]) ? :file_system : :db_file
94
+ attachment_options[:storage] ||= parent_options[:storage]
95
+ attachment_options[:path_prefix] ||= attachment_options[:file_system_path]
96
+ if attachment_options[:path_prefix].nil?
97
+ attachment_options[:path_prefix] = attachment_options[:storage] == :s3 ? table_name : File.join("public", table_name)
98
+ end
99
+ attachment_options[:path_prefix] = attachment_options[:path_prefix][1..-1] if options[:path_prefix].first == '/'
100
+
101
+ with_options :foreign_key => 'parent_id' do |m|
102
+ m.has_many :thumbnails, :class_name => "::#{attachment_options[:thumbnail_class]}"
103
+ m.belongs_to :parent, :class_name => "::#{base_class}" unless options[:thumbnails].empty?
104
+ end
105
+
106
+ storage_mod = Technoweenie::AttachmentFu::Backends.const_get("#{options[:storage].to_s.classify}Backend")
107
+ include storage_mod unless included_modules.include?(storage_mod)
108
+
109
+ case attachment_options[:processor]
110
+ when :none, nil
111
+ processors = Technoweenie::AttachmentFu.default_processors.dup
112
+ begin
113
+ if processors.any?
114
+ attachment_options[:processor] = "#{processors.first}Processor"
115
+ processor_mod = Technoweenie::AttachmentFu::Processors.const_get(attachment_options[:processor])
116
+ include processor_mod unless included_modules.include?(processor_mod)
117
+ end
118
+ rescue Object, Exception
119
+ raise unless load_related_exception?($!)
120
+
121
+ processors.shift
122
+ retry
123
+ end
124
+ else
125
+ begin
126
+ processor_mod = Technoweenie::AttachmentFu::Processors.const_get("#{attachment_options[:processor].to_s.classify}Processor")
127
+ include processor_mod unless included_modules.include?(processor_mod)
128
+ rescue Object, Exception
129
+ raise unless load_related_exception?($!)
130
+
131
+ puts "Problems loading #{options[:processor]}Processor: #{$!}"
132
+ end
133
+ end unless parent_options[:processor] # Don't let child override processor
134
+ end
135
+
136
+ def load_related_exception?(e) #:nodoc: implementation specific
137
+ case
138
+ when e.kind_of?(LoadError), e.kind_of?(MissingSourceFile), $!.class.name == "CompilationError"
139
+ # We can't rescue CompilationError directly, as it is part of the RubyInline library.
140
+ # We must instead rescue RuntimeError, and check the class' name.
141
+ true
142
+ else
143
+ false
144
+ end
145
+ end
146
+ private :load_related_exception?
147
+ end
148
+
149
+ module ClassMethods
150
+ delegate :content_types, :to => Technoweenie::AttachmentFu
151
+
152
+ # Performs common validations for attachment models.
153
+ def validates_as_attachment
154
+ validates_presence_of :size, :content_type, :filename
155
+ validate :attachment_attributes_valid?
156
+ end
157
+
158
+ # Returns true or false if the given content type is recognized as an image.
159
+ def image?(content_type)
160
+ content_types.include?(content_type)
161
+ end
162
+
163
+ def self.extended(base)
164
+ base.class_inheritable_accessor :attachment_options
165
+ base.before_destroy :destroy_thumbnails
166
+ base.before_validation :set_size_from_temp_path
167
+ base.after_save :after_process_attachment
168
+ base.after_destroy :destroy_file
169
+ base.after_validation :process_attachment
170
+ base.attr_accessible :uploaded_data
171
+ if defined?(::ActiveSupport::Callbacks)
172
+ base.define_callbacks :after_resize, :after_attachment_saved, :before_thumbnail_saved
173
+ end
174
+ end
175
+
176
+ unless defined?(::ActiveSupport::Callbacks)
177
+ # Callback after an image has been resized.
178
+ #
179
+ # class Foo < ActiveRecord::Base
180
+ # acts_as_attachment
181
+ # after_resize do |record, img|
182
+ # record.aspect_ratio = img.columns.to_f / img.rows.to_f
183
+ # end
184
+ # end
185
+ def after_resize(&block)
186
+ write_inheritable_array(:after_resize, [block])
187
+ end
188
+
189
+ # Callback after an attachment has been saved either to the file system or the DB.
190
+ # Only called if the file has been changed, not necessarily if the record is updated.
191
+ #
192
+ # class Foo < ActiveRecord::Base
193
+ # acts_as_attachment
194
+ # after_attachment_saved do |record|
195
+ # ...
196
+ # end
197
+ # end
198
+ def after_attachment_saved(&block)
199
+ write_inheritable_array(:after_attachment_saved, [block])
200
+ end
201
+
202
+ # Callback before a thumbnail is saved. Use this to pass any necessary extra attributes that may be required.
203
+ #
204
+ # class Foo < ActiveRecord::Base
205
+ # acts_as_attachment
206
+ # before_thumbnail_saved do |thumbnail|
207
+ # record = thumbnail.parent
208
+ # ...
209
+ # end
210
+ # end
211
+ def before_thumbnail_saved(&block)
212
+ write_inheritable_array(:before_thumbnail_saved, [block])
213
+ end
214
+ end
215
+
216
+ # Get the thumbnail class, which is the current attachment class by default.
217
+ # Configure this with the :thumbnail_class option.
218
+ def thumbnail_class
219
+ attachment_options[:thumbnail_class] = attachment_options[:thumbnail_class].constantize unless attachment_options[:thumbnail_class].is_a?(Class)
220
+ attachment_options[:thumbnail_class]
221
+ end
222
+
223
+ # Copies the given file path to a new tempfile, returning the closed tempfile.
224
+ def copy_to_temp_file(file, temp_base_name)
225
+ returning Tempfile.new(temp_base_name, Technoweenie::AttachmentFu.tempfile_path) do |tmp|
226
+ tmp.close
227
+ FileUtils.cp file, tmp.path
228
+ end
229
+ end
230
+
231
+ # Writes the given data to a new tempfile, returning the closed tempfile.
232
+ def write_to_temp_file(data, temp_base_name)
233
+ returning Tempfile.new(temp_base_name, Technoweenie::AttachmentFu.tempfile_path) do |tmp|
234
+ tmp.binmode
235
+ tmp.write data
236
+ tmp.close
237
+ end
238
+ end
239
+ end
240
+
241
+ module InstanceMethods
242
+ def self.included(base)
243
+ base.define_callbacks *[:after_resize, :after_attachment_saved, :before_thumbnail_saved] if base.respond_to?(:define_callbacks)
244
+ end
245
+
246
+ # Checks whether the attachment's content type is an image content type
247
+ def image?
248
+ self.class.image?(content_type)
249
+ end
250
+
251
+ # Returns true/false if an attachment is thumbnailable. A thumbnailable attachment has an image content type and the parent_id attribute.
252
+ def thumbnailable?
253
+ image? && respond_to?(:parent_id) && parent_id.nil?
254
+ end
255
+
256
+ # Returns the class used to create new thumbnails for this attachment.
257
+ def thumbnail_class
258
+ self.class.thumbnail_class
259
+ end
260
+
261
+ # Gets the thumbnail name for a filename. 'foo.jpg' becomes 'foo_thumbnail.jpg'
262
+ def thumbnail_name_for(thumbnail = nil)
263
+ return filename if thumbnail.blank?
264
+ ext = nil
265
+ basename = filename.gsub /\.\w+$/ do |s|
266
+ ext = s; ''
267
+ end
268
+ # ImageScience doesn't create gif thumbnails, only pngs
269
+ ext.sub!(/gif$/, 'png') if attachment_options[:processor] == "ImageScience"
270
+ "#{basename}_#{thumbnail}#{ext}"
271
+ end
272
+
273
+ # Creates or updates the thumbnail for the current attachment.
274
+ def create_or_update_thumbnail(temp_file, file_name_suffix, *size)
275
+ thumbnailable? || raise(ThumbnailError.new("Can't create a thumbnail if the content type is not an image or there is no parent_id column"))
276
+ returning find_or_initialize_thumbnail(file_name_suffix) do |thumb|
277
+ thumb.temp_paths.unshift temp_file
278
+ thumb.send(:'attributes=', {
279
+ :content_type => content_type,
280
+ :filename => thumbnail_name_for(file_name_suffix),
281
+ :thumbnail_resize_options => size
282
+ }, false)
283
+ callback_with_args :before_thumbnail_saved, thumb
284
+ thumb.save!
285
+ end
286
+ end
287
+
288
+ # Sets the content type.
289
+ def content_type=(new_type)
290
+ write_attribute :content_type, new_type.to_s.strip
291
+ end
292
+
293
+ # Sanitizes a filename.
294
+ def filename=(new_name)
295
+ write_attribute :filename, sanitize_filename(new_name)
296
+ end
297
+
298
+ # Returns the width/height in a suitable format for the image_tag helper: (100x100)
299
+ def image_size
300
+ [width.to_s, height.to_s] * 'x'
301
+ end
302
+
303
+ # Returns true if the attachment data will be written to the storage system on the next save
304
+ def save_attachment?
305
+ File.file?(temp_path.to_s)
306
+ end
307
+
308
+ # nil placeholder in case this field is used in a form.
309
+ def uploaded_data() nil; end
310
+
311
+ # This method handles the uploaded file object. If you set the field name to uploaded_data, you don't need
312
+ # any special code in your controller.
313
+ #
314
+ # <% form_for :attachment, :html => { :multipart => true } do |f| -%>
315
+ # <p><%= f.file_field :uploaded_data %></p>
316
+ # <p><%= submit_tag :Save %>
317
+ # <% end -%>
318
+ #
319
+ # @attachment = Attachment.create! params[:attachment]
320
+ #
321
+ # TODO: Allow it to work with Merb tempfiles too.
322
+ def uploaded_data=(file_data)
323
+ if file_data.respond_to?(:content_type)
324
+ return nil if file_data.size == 0
325
+ self.content_type = file_data.content_type
326
+ self.filename = file_data.original_filename if respond_to?(:filename)
327
+ else
328
+ return nil if file_data.blank? || file_data['size'] == 0
329
+ self.content_type = file_data['content_type']
330
+ self.filename = file_data['filename']
331
+ file_data = file_data['tempfile']
332
+ end
333
+ if file_data.is_a?(StringIO)
334
+ file_data.rewind
335
+ set_temp_data file_data.read
336
+ else
337
+ self.temp_paths.unshift file_data
338
+ end
339
+ end
340
+
341
+ # Gets the latest temp path from the collection of temp paths. While working with an attachment,
342
+ # multiple Tempfile objects may be created for various processing purposes (resizing, for example).
343
+ # An array of all the tempfile objects is stored so that the Tempfile instance is held on to until
344
+ # it's not needed anymore. The collection is cleared after saving the attachment.
345
+ def temp_path
346
+ p = temp_paths.first
347
+ p.respond_to?(:path) ? p.path : p.to_s
348
+ end
349
+
350
+ # Gets an array of the currently used temp paths. Defaults to a copy of #full_filename.
351
+ def temp_paths
352
+ @temp_paths ||= (new_record? || !respond_to?(:full_filename) || !File.exist?(full_filename) ?
353
+ [] : [copy_to_temp_file(full_filename)])
354
+ end
355
+
356
+ # Gets the data from the latest temp file. This will read the file into memory.
357
+ def temp_data
358
+ save_attachment? ? File.read(temp_path) : nil
359
+ end
360
+
361
+ # Writes the given data to a Tempfile and adds it to the collection of temp files.
362
+ def set_temp_data(data)
363
+ temp_paths.unshift write_to_temp_file data unless data.nil?
364
+ end
365
+
366
+ # Copies the given file to a randomly named Tempfile.
367
+ def copy_to_temp_file(file)
368
+ self.class.copy_to_temp_file file, random_tempfile_filename
369
+ end
370
+
371
+ # Writes the given file to a randomly named Tempfile.
372
+ def write_to_temp_file(data)
373
+ self.class.write_to_temp_file data, random_tempfile_filename
374
+ end
375
+
376
+ # Stub for creating a temp file from the attachment data. This should be defined in the backend module.
377
+ def create_temp_file() end
378
+
379
+ # Allows you to work with a processed representation (RMagick, ImageScience, etc) of the attachment in a block.
380
+ #
381
+ # @attachment.with_image do |img|
382
+ # self.data = img.thumbnail(100, 100).to_blob
383
+ # end
384
+ #
385
+ def with_image(&block)
386
+ self.class.with_image(temp_path, &block)
387
+ end
388
+
389
+ protected
390
+ # Generates a unique filename for a Tempfile.
391
+ def random_tempfile_filename
392
+ "#{rand Time.now.to_i}#{filename || 'attachment'}"
393
+ end
394
+
395
+ def sanitize_filename(filename)
396
+ return unless filename
397
+ returning filename.strip do |name|
398
+ # NOTE: File.basename doesn't work right with Windows paths on Unix
399
+ # get only the filename, not the whole path
400
+ name.gsub! /^.*(\\|\/)/, ''
401
+
402
+ # Finally, replace all non alphanumeric, underscore or periods with underscore
403
+ name.gsub! /[^A-Za-z0-9\.\-]/, '_'
404
+ end
405
+ end
406
+
407
+ # before_validation callback.
408
+ def set_size_from_temp_path
409
+ self.size = File.size(temp_path) if save_attachment?
410
+ end
411
+
412
+ # validates the size and content_type attributes according to the current model's options
413
+ def attachment_attributes_valid?
414
+ [:size, :content_type].each do |attr_name|
415
+ enum = attachment_options[attr_name]
416
+ errors.add attr_name, ActiveRecord::Errors.default_error_messages[:inclusion] unless enum.nil? || enum.include?(send(attr_name))
417
+ end
418
+ end
419
+
420
+ # Initializes a new thumbnail with the given suffix.
421
+ def find_or_initialize_thumbnail(file_name_suffix)
422
+ respond_to?(:parent_id) ?
423
+ thumbnail_class.find_or_initialize_by_thumbnail_and_parent_id(file_name_suffix.to_s, id) :
424
+ thumbnail_class.find_or_initialize_by_thumbnail(file_name_suffix.to_s)
425
+ end
426
+
427
+ # Stub for a #process_attachment method in a processor
428
+ def process_attachment
429
+ @saved_attachment = save_attachment?
430
+ end
431
+
432
+ # Cleans up after processing. Thumbnails are created, the attachment is stored to the backend, and the temp_paths are cleared.
433
+ def after_process_attachment
434
+ if @saved_attachment
435
+ if respond_to?(:process_attachment_with_processing) && thumbnailable? && !attachment_options[:thumbnails].blank? && parent_id.nil?
436
+ temp_file = temp_path || create_temp_file
437
+ attachment_options[:thumbnails].each { |suffix, size| create_or_update_thumbnail(temp_file, suffix, *size) }
438
+ end
439
+ save_to_storage
440
+ @temp_paths.clear
441
+ @saved_attachment = nil
442
+ callback :after_attachment_saved
443
+ end
444
+ end
445
+
446
+ # Resizes the given processed img object with either the attachment resize options or the thumbnail resize options.
447
+ def resize_image_or_thumbnail!(img)
448
+ if (!respond_to?(:parent_id) || parent_id.nil?) && attachment_options[:resize_to] # parent image
449
+ resize_image(img, attachment_options[:resize_to])
450
+ elsif thumbnail_resize_options # thumbnail
451
+ resize_image(img, thumbnail_resize_options)
452
+ end
453
+ end
454
+
455
+ # Yanked from ActiveRecord::Callbacks, modified so I can pass args to the callbacks besides self.
456
+ # Only accept blocks, however
457
+ if ActiveSupport.const_defined?(:Callbacks)
458
+ # Rails 2.1 and beyond!
459
+ def callback_with_args(method, arg = self)
460
+ notify(method)
461
+
462
+ result = run_callbacks(method, { :object => arg }) { |result, object| result == false }
463
+
464
+ if result != false && respond_to_without_attributes?(method)
465
+ result = send(method)
466
+ end
467
+
468
+ result
469
+ end
470
+
471
+ def run_callbacks(kind, options = {}, &block)
472
+ options.reverse_merge!( :object => self )
473
+ self.class.send("#{kind}_callback_chain").run(options[:object], options, &block)
474
+ end
475
+ else
476
+ # Rails 2.0
477
+ def callback_with_args(method, arg = self)
478
+ notify(method)
479
+
480
+ result = nil
481
+ callbacks_for(method).each do |callback|
482
+ result = callback.call(self, arg)
483
+ return false if result == false
484
+ end
485
+ result
486
+ end
487
+ end
488
+
489
+ # Removes the thumbnails for the attachment, if it has any
490
+ def destroy_thumbnails
491
+ self.thumbnails.each { |thumbnail| thumbnail.destroy } if thumbnailable?
492
+ end
493
+ end
494
+ end
495
+ end