ss-attachment_fu 3.2.17
Sign up to get free protection for your applications and to get access to all the features.
- data/CHANGELOG +99 -0
- data/LICENSE +20 -0
- data/README.rdoc +358 -0
- data/amazon_s3.yml.tpl +17 -0
- data/lib/geometry.rb +96 -0
- data/lib/pothoven-attachment_fu.rb +27 -0
- data/lib/technoweenie/attachment_fu/backends/cloud_file_backend.rb +212 -0
- data/lib/technoweenie/attachment_fu/backends/db_file_backend.rb +40 -0
- data/lib/technoweenie/attachment_fu/backends/file_system_backend.rb +157 -0
- data/lib/technoweenie/attachment_fu/backends/s3_backend.rb +413 -0
- data/lib/technoweenie/attachment_fu/processors/core_image_processor.rb +66 -0
- data/lib/technoweenie/attachment_fu/processors/gd2_processor.rb +59 -0
- data/lib/technoweenie/attachment_fu/processors/image_science_processor.rb +80 -0
- data/lib/technoweenie/attachment_fu/processors/mini_magick_processor.rb +142 -0
- data/lib/technoweenie/attachment_fu/processors/rmagick_processor.rb +66 -0
- data/lib/technoweenie/attachment_fu.rb +625 -0
- data/rackspace_cloudfiles.yml.tpl +14 -0
- data/vendor/red_artisan/core_image/filters/color.rb +27 -0
- data/vendor/red_artisan/core_image/filters/effects.rb +31 -0
- data/vendor/red_artisan/core_image/filters/perspective.rb +25 -0
- data/vendor/red_artisan/core_image/filters/quality.rb +25 -0
- data/vendor/red_artisan/core_image/filters/scale.rb +47 -0
- data/vendor/red_artisan/core_image/filters/watermark.rb +32 -0
- data/vendor/red_artisan/core_image/processor.rb +123 -0
- metadata +73 -0
@@ -0,0 +1,625 @@
|
|
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
|
+
'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
|
+
options[:cache_control] ||= "max-age=315360000" # 10 years
|
102
|
+
|
103
|
+
unless options[:thumbnails].is_a?(Hash)
|
104
|
+
raise ArgumentError, ":thumbnails option should be a hash: e.g. :thumbnails => { :foo => '50x50' }"
|
105
|
+
end
|
106
|
+
|
107
|
+
extend ClassMethods unless (class << self; included_modules; end).include?(ClassMethods)
|
108
|
+
include InstanceMethods unless included_modules.include?(InstanceMethods)
|
109
|
+
|
110
|
+
parent_options = attachment_options || {}
|
111
|
+
# doing these shenanigans so that #attachment_options is available to processors and backends
|
112
|
+
self.attachment_options = options
|
113
|
+
|
114
|
+
attr_accessor :thumbnail_resize_options
|
115
|
+
|
116
|
+
attachment_options[:storage] ||= (attachment_options[:file_system_path] || attachment_options[:path_prefix]) ? :file_system : :db_file
|
117
|
+
attachment_options[:storage] ||= parent_options[:storage]
|
118
|
+
attachment_options[:path_prefix] ||= attachment_options[:file_system_path]
|
119
|
+
if attachment_options[:path_prefix].nil?
|
120
|
+
attachment_options[:path_prefix] = case attachment_options[:storage]
|
121
|
+
when :s3 then table_name
|
122
|
+
when :cloud_files then table_name
|
123
|
+
else File.join("public", table_name)
|
124
|
+
end
|
125
|
+
end
|
126
|
+
attachment_options[:path_prefix] = attachment_options[:path_prefix][1..-1] if options[:path_prefix].first == '/'
|
127
|
+
|
128
|
+
association_options = { :foreign_key => 'parent_id' }
|
129
|
+
if attachment_options[:association_options]
|
130
|
+
association_options.merge!(attachment_options[:association_options])
|
131
|
+
end
|
132
|
+
with_options(association_options) do |m|
|
133
|
+
m.has_many :thumbnails, :class_name => "::#{attachment_options[:thumbnail_class]}"
|
134
|
+
m.belongs_to :parent, :class_name => "::#{base_class}" unless options[:thumbnails].empty?
|
135
|
+
end
|
136
|
+
|
137
|
+
storage_mod = ::Technoweenie::AttachmentFu::Backends.const_get("#{options[:storage].to_s.classify}Backend")
|
138
|
+
include storage_mod unless included_modules.include?(storage_mod)
|
139
|
+
|
140
|
+
case attachment_options[:processor]
|
141
|
+
when :none, nil
|
142
|
+
processors = ::Technoweenie::AttachmentFu.default_processors.dup
|
143
|
+
begin
|
144
|
+
if processors.any?
|
145
|
+
attachment_options[:processor] = processors.first
|
146
|
+
processor_mod = ::Technoweenie::AttachmentFu::Processors.const_get("#{attachment_options[:processor].to_s.classify}Processor")
|
147
|
+
include processor_mod unless included_modules.include?(processor_mod)
|
148
|
+
end
|
149
|
+
rescue Object, Exception
|
150
|
+
raise unless load_related_exception?($!)
|
151
|
+
|
152
|
+
processors.shift
|
153
|
+
retry
|
154
|
+
end
|
155
|
+
else
|
156
|
+
begin
|
157
|
+
processor_mod = ::Technoweenie::AttachmentFu::Processors.const_get("#{attachment_options[:processor].to_s.classify}Processor")
|
158
|
+
include processor_mod unless included_modules.include?(processor_mod)
|
159
|
+
rescue Object, Exception
|
160
|
+
raise unless load_related_exception?($!)
|
161
|
+
|
162
|
+
puts "Problems loading #{options[:processor]}Processor: #{$!}"
|
163
|
+
end
|
164
|
+
end unless parent_options[:processor] # Don't let child override processor
|
165
|
+
end
|
166
|
+
|
167
|
+
def load_related_exception?(e) #:nodoc: implementation specific
|
168
|
+
case
|
169
|
+
when e.kind_of?(LoadError), e.kind_of?(MissingSourceFile), $!.class.name == "CompilationError"
|
170
|
+
# We can't rescue CompilationError directly, as it is part of the RubyInline library.
|
171
|
+
# We must instead rescue RuntimeError, and check the class' name.
|
172
|
+
true
|
173
|
+
else
|
174
|
+
false
|
175
|
+
end
|
176
|
+
end
|
177
|
+
private :load_related_exception?
|
178
|
+
end
|
179
|
+
|
180
|
+
module ClassMethods
|
181
|
+
delegate :content_types, :to => ::Technoweenie::AttachmentFu
|
182
|
+
|
183
|
+
# Performs common validations for attachment models.
|
184
|
+
def validates_as_attachment
|
185
|
+
validates_presence_of :size, :content_type, :filename
|
186
|
+
validate :attachment_attributes_valid?
|
187
|
+
end
|
188
|
+
|
189
|
+
# Returns true or false if the given content type is recognized as an image.
|
190
|
+
def image?(content_type)
|
191
|
+
content_types.include?(content_type)
|
192
|
+
end
|
193
|
+
|
194
|
+
def self.extended(base)
|
195
|
+
base.class_attribute :attachment_options
|
196
|
+
base.before_destroy :destroy_thumbnails
|
197
|
+
base.before_validation :set_size_from_temp_path
|
198
|
+
base.after_destroy :destroy_file
|
199
|
+
base.after_validation :process_attachment
|
200
|
+
base.after_save :after_process_attachment
|
201
|
+
#if defined?(::ActiveSupport::Callbacks)
|
202
|
+
# base.define_callbacks :after_resize, :after_attachment_saved, :before_thumbnail_saved
|
203
|
+
#end
|
204
|
+
end
|
205
|
+
|
206
|
+
unless defined?(::ActiveSupport::Callbacks)
|
207
|
+
# Callback after an image has been resized.
|
208
|
+
#
|
209
|
+
# class Foo < ActiveRecord::Base
|
210
|
+
# acts_as_attachment
|
211
|
+
# after_resize do |record, img|
|
212
|
+
# record.aspect_ratio = img.columns.to_f / img.rows.to_f
|
213
|
+
# end
|
214
|
+
# end
|
215
|
+
def after_resize(&block)
|
216
|
+
write_inheritable_array(:after_resize, [block])
|
217
|
+
end
|
218
|
+
|
219
|
+
# Callback after an attachment has been saved either to the file system or the DB.
|
220
|
+
# Only called if the file has been changed, not necessarily if the record is updated.
|
221
|
+
#
|
222
|
+
# class Foo < ActiveRecord::Base
|
223
|
+
# acts_as_attachment
|
224
|
+
# after_attachment_saved do |record|
|
225
|
+
# ...
|
226
|
+
# end
|
227
|
+
# end
|
228
|
+
def after_attachment_saved(&block)
|
229
|
+
write_inheritable_array(:after_attachment_saved, [block])
|
230
|
+
end
|
231
|
+
|
232
|
+
# Callback before a thumbnail is saved. Use this to pass any necessary extra attributes that may be required.
|
233
|
+
#
|
234
|
+
# class Foo < ActiveRecord::Base
|
235
|
+
# acts_as_attachment
|
236
|
+
# before_thumbnail_saved do |thumbnail|
|
237
|
+
# record = thumbnail.parent
|
238
|
+
# ...
|
239
|
+
# end
|
240
|
+
# end
|
241
|
+
def before_thumbnail_saved(&block)
|
242
|
+
write_inheritable_array(:before_thumbnail_saved, [block])
|
243
|
+
end
|
244
|
+
end
|
245
|
+
|
246
|
+
# Get the thumbnail class, which is the current attachment class by default.
|
247
|
+
# Configure this with the :thumbnail_class option.
|
248
|
+
def thumbnail_class
|
249
|
+
attachment_options[:thumbnail_class] = attachment_options[:thumbnail_class].constantize unless attachment_options[:thumbnail_class].is_a?(Class)
|
250
|
+
attachment_options[:thumbnail_class]
|
251
|
+
end
|
252
|
+
|
253
|
+
# Copies the given file path to a new tempfile, returning the closed tempfile.
|
254
|
+
def copy_to_temp_file(file, temp_base_name)
|
255
|
+
Tempfile.new(temp_base_name, ::Technoweenie::AttachmentFu.tempfile_path).tap do |tmp|
|
256
|
+
tmp.close
|
257
|
+
FileUtils.cp file, tmp.path
|
258
|
+
end
|
259
|
+
end
|
260
|
+
|
261
|
+
# Writes the given data to a new tempfile, returning the closed tempfile.
|
262
|
+
def write_to_temp_file(data, temp_base_name)
|
263
|
+
Tempfile.new(temp_base_name, ::Technoweenie::AttachmentFu.tempfile_path).tap do |tmp|
|
264
|
+
tmp.binmode
|
265
|
+
tmp.write data
|
266
|
+
tmp.close
|
267
|
+
end
|
268
|
+
end
|
269
|
+
|
270
|
+
def polymorphic_relation_type_column
|
271
|
+
return @@_polymorphic_relation_type_column if defined?(@@_polymorphic_relation_type_column)
|
272
|
+
# Checked against ActiveRecord 1.15.6 through Edge @ 2009-08-05.
|
273
|
+
ref = reflections.values.detect { |r| r.macro == :belongs_to && r.options[:polymorphic] }
|
274
|
+
@@_polymorphic_relation_type_column = ref && ref.options[:foreign_type]
|
275
|
+
end
|
276
|
+
end
|
277
|
+
|
278
|
+
module InstanceMethods
|
279
|
+
def self.included(base)
|
280
|
+
base.define_callbacks *[:after_resize, :after_attachment_saved, :before_thumbnail_saved] if base.respond_to?(:define_callbacks)
|
281
|
+
end
|
282
|
+
|
283
|
+
# Checks whether the attachment's content type is an image content type
|
284
|
+
def image?
|
285
|
+
self.class.image?(content_type)
|
286
|
+
end
|
287
|
+
|
288
|
+
# Returns true/false if an attachment is thumbnailable. A thumbnailable attachment has an image content type and the parent_id attribute.
|
289
|
+
def thumbnailable?
|
290
|
+
image? && respond_to?(:parent_id) && parent_id.nil?
|
291
|
+
end
|
292
|
+
|
293
|
+
# Returns the class used to create new thumbnails for this attachment.
|
294
|
+
def thumbnail_class
|
295
|
+
self.class.thumbnail_class
|
296
|
+
end
|
297
|
+
|
298
|
+
# Gets the thumbnail name for a filename. 'foo.jpg' becomes 'foo_thumbnail.jpg'
|
299
|
+
def thumbnail_name_for(thumbnail = nil)
|
300
|
+
if thumbnail.blank?
|
301
|
+
if filename.nil?
|
302
|
+
return ''
|
303
|
+
else
|
304
|
+
return filename
|
305
|
+
end
|
306
|
+
end
|
307
|
+
|
308
|
+
ext = nil
|
309
|
+
basename = filename.gsub /\.\w+$/ do |s|
|
310
|
+
ext = s; ''
|
311
|
+
end
|
312
|
+
# ImageScience doesn't create gif thumbnails, only pngs
|
313
|
+
ext.sub!(/gif$/i, 'png') if attachment_options[:processor] == "ImageScience"
|
314
|
+
"#{basename}_#{thumbnail}#{ext}"
|
315
|
+
end
|
316
|
+
|
317
|
+
# Creates or updates the thumbnail for the current attachment.
|
318
|
+
def create_or_update_thumbnail(temp_file, file_name_suffix, *size)
|
319
|
+
thumbnailable? || raise(ThumbnailError.new("Can't create a thumbnail if the content type is not an image or there is no parent_id column"))
|
320
|
+
find_or_initialize_thumbnail(file_name_suffix).tap do |thumb|
|
321
|
+
thumb.temp_paths.unshift temp_file
|
322
|
+
assign_attributes_args = []
|
323
|
+
assign_attributes_args << {
|
324
|
+
:content_type => content_type,
|
325
|
+
:filename => thumbnail_name_for(file_name_suffix),
|
326
|
+
:thumbnail_resize_options => size
|
327
|
+
}
|
328
|
+
if defined?(Rails) && Rails::VERSION::MAJOR == 3
|
329
|
+
# assign_attributes API in Rails 2.3 doesn't take a second argument
|
330
|
+
assign_attributes_args << { :without_protection => true }
|
331
|
+
end
|
332
|
+
thumb.send(:assign_attributes, *assign_attributes_args)
|
333
|
+
callback_with_args :before_thumbnail_saved, thumb
|
334
|
+
thumb.save!
|
335
|
+
end
|
336
|
+
end
|
337
|
+
|
338
|
+
# Sets the content type.
|
339
|
+
def content_type=(new_type)
|
340
|
+
write_attribute :content_type, new_type.to_s.strip
|
341
|
+
end
|
342
|
+
|
343
|
+
# Sanitizes a filename.
|
344
|
+
def filename=(new_name)
|
345
|
+
write_attribute :filename, sanitize_filename(new_name)
|
346
|
+
end
|
347
|
+
|
348
|
+
# Returns the width/height in a suitable format for the image_tag helper: (100x100)
|
349
|
+
def image_size
|
350
|
+
[width.to_s, height.to_s] * 'x'
|
351
|
+
end
|
352
|
+
|
353
|
+
# Returns true if the attachment data will be written to the storage system on the next save
|
354
|
+
def save_attachment?
|
355
|
+
File.file?(temp_path.class == String ? temp_path : temp_path.to_filename)
|
356
|
+
end
|
357
|
+
|
358
|
+
# nil placeholder in case this field is used in a form.
|
359
|
+
def uploaded_data() nil; end
|
360
|
+
|
361
|
+
# This method handles the uploaded file object. If you set the field name to uploaded_data, you don't need
|
362
|
+
# any special code in your controller.
|
363
|
+
#
|
364
|
+
# <% form_for :attachment, :html => { :multipart => true } do |f| -%>
|
365
|
+
# <p><%= f.file_field :uploaded_data %></p>
|
366
|
+
# <p><%= submit_tag :Save %>
|
367
|
+
# <% end -%>
|
368
|
+
#
|
369
|
+
# @attachment = Attachment.create! params[:attachment]
|
370
|
+
#
|
371
|
+
# TODO: Allow it to work with Merb tempfiles too.
|
372
|
+
def uploaded_data=(file_data)
|
373
|
+
if file_data.respond_to?(:content_type)
|
374
|
+
return nil if file_data.size == 0
|
375
|
+
self.content_type = file_data.content_type
|
376
|
+
self.filename = file_data.original_filename if respond_to?(:filename)
|
377
|
+
else
|
378
|
+
return nil if file_data.blank? || file_data['size'] == 0
|
379
|
+
self.content_type = file_data['content_type']
|
380
|
+
self.filename = file_data['filename']
|
381
|
+
file_data = file_data['tempfile']
|
382
|
+
end
|
383
|
+
if file_data.is_a?(StringIO)
|
384
|
+
file_data.rewind
|
385
|
+
set_temp_data file_data.read
|
386
|
+
else
|
387
|
+
file_data.respond_to?(:tempfile) ? self.temp_paths.unshift( file_data.tempfile.path ) : self.temp_paths.unshift( file_data.path )
|
388
|
+
end
|
389
|
+
end
|
390
|
+
|
391
|
+
# Gets the latest temp path from the collection of temp paths. While working with an attachment,
|
392
|
+
# multiple Tempfile objects may be created for various processing purposes (resizing, for example).
|
393
|
+
# An array of all the tempfile objects is stored so that the Tempfile instance is held on to until
|
394
|
+
# it's not needed anymore. The collection is cleared after saving the attachment.
|
395
|
+
def temp_path
|
396
|
+
p = temp_paths.first
|
397
|
+
p.respond_to?(:path) ? p.path : p.to_s
|
398
|
+
end
|
399
|
+
|
400
|
+
# Gets an array of the currently used temp paths. Defaults to a copy of #full_filename.
|
401
|
+
def temp_paths
|
402
|
+
@temp_paths ||= (new_record? || !respond_to?(:full_filename) || !File.exist?(full_filename) ?
|
403
|
+
[] : [copy_to_temp_file(full_filename)])
|
404
|
+
end
|
405
|
+
|
406
|
+
# Gets the data from the latest temp file. This will read the file into memory.
|
407
|
+
def temp_data
|
408
|
+
save_attachment? ? File.read(temp_path) : nil
|
409
|
+
end
|
410
|
+
|
411
|
+
# Writes the given data to a Tempfile and adds it to the collection of temp files.
|
412
|
+
def set_temp_data(data)
|
413
|
+
temp_paths.unshift write_to_temp_file data unless data.nil?
|
414
|
+
end
|
415
|
+
|
416
|
+
# Copies the given file to a randomly named Tempfile.
|
417
|
+
def copy_to_temp_file(file)
|
418
|
+
self.class.copy_to_temp_file file, random_tempfile_filename
|
419
|
+
end
|
420
|
+
|
421
|
+
# Writes the given file to a randomly named Tempfile.
|
422
|
+
def write_to_temp_file(data)
|
423
|
+
self.class.write_to_temp_file data, random_tempfile_filename
|
424
|
+
end
|
425
|
+
|
426
|
+
# Stub for creating a temp file from the attachment data. This should be defined in the backend module.
|
427
|
+
def create_temp_file() end
|
428
|
+
|
429
|
+
# Allows you to work with a processed representation (RMagick, ImageScience, etc) of the attachment in a block.
|
430
|
+
#
|
431
|
+
# @attachment.with_image do |img|
|
432
|
+
# self.data = img.thumbnail(100, 100).to_blob
|
433
|
+
# end
|
434
|
+
#
|
435
|
+
def with_image(&block)
|
436
|
+
# Write out the temporary data if it is not present
|
437
|
+
if temp_data.nil?
|
438
|
+
self.temp_data = current_data
|
439
|
+
end
|
440
|
+
|
441
|
+
self.class.with_image(temp_path, &block)
|
442
|
+
end
|
443
|
+
|
444
|
+
protected
|
445
|
+
# Generates a unique filename for a Tempfile.
|
446
|
+
def random_tempfile_filename
|
447
|
+
base_filename = filename ? filename.gsub(/\.\w+$/, '') : 'attachment'
|
448
|
+
ext = filename.slice(/\.\w+$/)
|
449
|
+
["#{rand Time.now.to_i}#{base_filename}", ext || '']
|
450
|
+
end
|
451
|
+
|
452
|
+
def sanitize_filename(filename)
|
453
|
+
return unless filename
|
454
|
+
filename.strip.tap do |name|
|
455
|
+
# NOTE: File.basename doesn't work right with Windows paths on Unix
|
456
|
+
# get only the filename, not the whole path
|
457
|
+
name.gsub! /^.*(\\|\/)/, ''
|
458
|
+
|
459
|
+
# Finally, replace all non alphanumeric, underscore or periods with underscore
|
460
|
+
name.gsub! /[^A-Za-z0-9\.\-]/, '_'
|
461
|
+
end
|
462
|
+
end
|
463
|
+
|
464
|
+
# before_validation callback.
|
465
|
+
def set_size_from_temp_path
|
466
|
+
self.size = File.size(temp_path) if save_attachment?
|
467
|
+
end
|
468
|
+
|
469
|
+
# validates the size and content_type attributes according to the current model's options
|
470
|
+
def attachment_attributes_valid?
|
471
|
+
[:size, :content_type].each do |attr_name|
|
472
|
+
enum = attachment_options[attr_name]
|
473
|
+
if Object.const_defined?(:I18n) # Rails >= 2.2
|
474
|
+
errors.add attr_name, I18n.translate("activerecord.errors.messages.inclusion", attr_name => enum) unless enum.nil? || enum.include?(send(attr_name))
|
475
|
+
else
|
476
|
+
errors.add attr_name, ActiveRecord::Errors.default_error_messages[:inclusion] unless enum.nil? || enum.include?(send(attr_name))
|
477
|
+
end
|
478
|
+
end
|
479
|
+
end
|
480
|
+
|
481
|
+
# Initializes a new thumbnail with the given suffix.
|
482
|
+
def find_or_initialize_thumbnail(file_name_suffix)
|
483
|
+
if defined?(Rails) && Rails::VERSION::MAJOR >= 4
|
484
|
+
respond_to?(:parent_id) ?
|
485
|
+
thumbnail_class.find_or_initialize_by(:thumbnail => file_name_suffix.to_s, :parent_id => id) :
|
486
|
+
thumbnail_class.find_or_initialize_by(:thumbnail => file_name_suffix.to_s)
|
487
|
+
else
|
488
|
+
respond_to?(:parent_id) ?
|
489
|
+
thumbnail_class.find_or_initialize_by_thumbnail_and_parent_id(file_name_suffix.to_s, id) :
|
490
|
+
thumbnail_class.find_or_initialize_by_thumbnail(file_name_suffix.to_s)
|
491
|
+
end
|
492
|
+
end
|
493
|
+
|
494
|
+
# Stub for a #process_attachment method in a processor
|
495
|
+
def process_attachment
|
496
|
+
@saved_attachment = save_attachment?
|
497
|
+
end
|
498
|
+
|
499
|
+
# Cleans up after processing. Thumbnails are created, the attachment is stored to the backend, and the temp_paths are cleared.
|
500
|
+
def after_process_attachment
|
501
|
+
if @saved_attachment
|
502
|
+
if respond_to?(:process_attachment_with_processing, true) && thumbnailable? && !attachment_options[:thumbnails].blank? && parent_id.nil?
|
503
|
+
temp_file = temp_path || create_temp_file
|
504
|
+
attachment_options[:thumbnails].each { |suffix, size|
|
505
|
+
if size.is_a?(Symbol)
|
506
|
+
parent_type = polymorphic_parent_type
|
507
|
+
next unless parent_type && [parent_type, parent_type.tableize].include?(suffix.to_s) && respond_to?(size)
|
508
|
+
size = send(size)
|
509
|
+
end
|
510
|
+
if size.is_a?(Hash)
|
511
|
+
parent_type = polymorphic_parent_type
|
512
|
+
next unless parent_type && [parent_type, parent_type.tableize].include?(suffix.to_s)
|
513
|
+
size.each { |ppt_suffix, ppt_size|
|
514
|
+
create_or_update_thumbnail(temp_file, ppt_suffix, *ppt_size)
|
515
|
+
}
|
516
|
+
else
|
517
|
+
create_or_update_thumbnail(temp_file, suffix, *size)
|
518
|
+
end
|
519
|
+
}
|
520
|
+
end
|
521
|
+
save_to_storage
|
522
|
+
@temp_paths.clear
|
523
|
+
@saved_attachment = nil
|
524
|
+
#callback :after_attachment_saved
|
525
|
+
callback_with_args :after_attachment_saved, nil
|
526
|
+
end
|
527
|
+
end
|
528
|
+
|
529
|
+
# Determine what the parameter is and handle it
|
530
|
+
# Options are
|
531
|
+
# 1. String "100x50"
|
532
|
+
# 2. Array [100,50]
|
533
|
+
# 2. Method to return one of the above
|
534
|
+
#
|
535
|
+
def evaluate_parameter(param)
|
536
|
+
return param if param.is_a?(String)
|
537
|
+
|
538
|
+
return param if param.is_a?(Array) && param.length > 1
|
539
|
+
|
540
|
+
param = param[0] if param.is_a?(Array)
|
541
|
+
|
542
|
+
if param.is_a?(Symbol) && self.respond_to?(param)
|
543
|
+
self.send param
|
544
|
+
else
|
545
|
+
param
|
546
|
+
end
|
547
|
+
end
|
548
|
+
|
549
|
+
# Resizes the given processed img object with either the attachment resize options or the thumbnail resize options.
|
550
|
+
def resize_image_or_thumbnail!(img)
|
551
|
+
if (!respond_to?(:parent_id) || parent_id.nil?) && attachment_options[:resize_to] # parent image
|
552
|
+
resize_image(img, evaluate_parameter(attachment_options[:resize_to]))
|
553
|
+
elsif thumbnail_resize_options # thumbnail
|
554
|
+
resize_image(img, evaluate_parameter(thumbnail_resize_options))
|
555
|
+
end
|
556
|
+
end
|
557
|
+
|
558
|
+
if defined?(Rails) && Rails::VERSION::MAJOR >= 3
|
559
|
+
def callback_with_args(method, arg = self)
|
560
|
+
if respond_to?(method)
|
561
|
+
send(method, arg)
|
562
|
+
end
|
563
|
+
end
|
564
|
+
# Yanked from ActiveRecord::Callbacks, modified so I can pass args to the callbacks besides self.
|
565
|
+
# Only accept blocks, however
|
566
|
+
elsif ActiveSupport.const_defined?(:Callbacks)
|
567
|
+
# Rails 2.1 and beyond!
|
568
|
+
def callback_with_args(method, arg = self)
|
569
|
+
notify(method)
|
570
|
+
|
571
|
+
result = run_callbacks(method, { :object => arg }) { |result, object| result == false }
|
572
|
+
|
573
|
+
if result != false && respond_to_without_attributes?(method)
|
574
|
+
result = send(method)
|
575
|
+
end
|
576
|
+
|
577
|
+
result
|
578
|
+
end
|
579
|
+
|
580
|
+
def run_callbacks(kind, options = {}, &block)
|
581
|
+
options.reverse_merge!( :object => self )
|
582
|
+
self.class.send("#{kind}_callback_chain").run(options[:object], options, &block)
|
583
|
+
end
|
584
|
+
else
|
585
|
+
# Rails 2.0
|
586
|
+
def callback_with_args(method, arg = self)
|
587
|
+
notify(method)
|
588
|
+
|
589
|
+
result = nil
|
590
|
+
callbacks_for(method).each do |callback|
|
591
|
+
result = callback.call(self, arg)
|
592
|
+
return false if result == false
|
593
|
+
end
|
594
|
+
result
|
595
|
+
end
|
596
|
+
end
|
597
|
+
|
598
|
+
# Removes the thumbnails for the attachment, if it has any
|
599
|
+
def destroy_thumbnails
|
600
|
+
self.thumbnails.each { |thumbnail| thumbnail.destroy } if thumbnailable?
|
601
|
+
end
|
602
|
+
|
603
|
+
def polymorphic_parent_type
|
604
|
+
rel_name = self.class.polymorphic_relation_type_column
|
605
|
+
rel_name && send(rel_name)
|
606
|
+
end
|
607
|
+
|
608
|
+
def get_jpeg_quality(require_0_to_100 = true)
|
609
|
+
quality = attachment_options[:jpeg_quality]
|
610
|
+
if quality.is_a?(Hash)
|
611
|
+
sbl_quality = thumbnail && quality[thumbnail.to_sym]
|
612
|
+
sbl_quality = nil if sbl_quality && require_0_to_100 && !sbl_quality.to_i.between?(0, 100)
|
613
|
+
surface = (width || 1) * (height || 1)
|
614
|
+
size_quality = quality.detect { |k, v|
|
615
|
+
next unless k.is_a?(String) && k =~ /^(<|>=)(\d+)$/
|
616
|
+
op, threshold = $1, $2.to_i
|
617
|
+
surface.send(op, threshold)
|
618
|
+
}
|
619
|
+
quality = sbl_quality || size_quality && size_quality[1]
|
620
|
+
end
|
621
|
+
return quality && (!require_0_to_100 || quality.to_i.between?(0, 100)) ? quality : nil
|
622
|
+
end
|
623
|
+
end
|
624
|
+
end
|
625
|
+
end
|
@@ -0,0 +1,27 @@
|
|
1
|
+
module RedArtisan
|
2
|
+
module CoreImage
|
3
|
+
module Filters
|
4
|
+
module Color
|
5
|
+
|
6
|
+
def greyscale(color = nil, intensity = 1.00)
|
7
|
+
create_core_image_context(@original.extent.size.width, @original.extent.size.height)
|
8
|
+
|
9
|
+
color = OSX::CIColor.colorWithString("1.0 1.0 1.0 1.0") unless color
|
10
|
+
|
11
|
+
@original.color_monochrome :inputColor => color, :inputIntensity => intensity do |greyscale|
|
12
|
+
@target = greyscale
|
13
|
+
end
|
14
|
+
end
|
15
|
+
|
16
|
+
def sepia(intensity = 1.00)
|
17
|
+
create_core_image_context(@original.extent.size.width, @original.extent.size.height)
|
18
|
+
|
19
|
+
@original.sepia_tone :inputIntensity => intensity do |sepia|
|
20
|
+
@target = sepia
|
21
|
+
end
|
22
|
+
end
|
23
|
+
|
24
|
+
end
|
25
|
+
end
|
26
|
+
end
|
27
|
+
end
|