attachment_zen 1.0.1
Sign up to get free protection for your applications and to get access to all the features.
- checksums.yaml +7 -0
- data/CHANGELOG +35 -0
- data/README.md +227 -0
- data/lib/attachment_fu.rb +8 -0
- data/lib/technoweenie/attachment_fu.rb +771 -0
- data/lib/technoweenie/attachment_fu/backends/backend_delegator.rb +19 -0
- data/lib/technoweenie/attachment_fu/backends/cloud_file_backend.rb +245 -0
- data/lib/technoweenie/attachment_fu/backends/db_file_backend.rb +36 -0
- data/lib/technoweenie/attachment_fu/backends/file_system_backend.rb +125 -0
- data/lib/technoweenie/attachment_fu/backends/mogile_fs_backend.rb +99 -0
- data/lib/technoweenie/attachment_fu/backends/s3_backend.rb +394 -0
- data/lib/technoweenie/attachment_fu/geometry.rb +93 -0
- data/lib/technoweenie/attachment_fu/processors/core_image_processor.rb +56 -0
- data/lib/technoweenie/attachment_fu/processors/gd2_processor.rb +52 -0
- data/lib/technoweenie/attachment_fu/processors/image_science_processor.rb +59 -0
- data/lib/technoweenie/attachment_fu/processors/mini_magick_processor.rb +126 -0
- data/lib/technoweenie/attachment_fu/processors/rmagick_processor.rb +54 -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 +122 -0
- metadata +255 -0
checksums.yaml
ADDED
@@ -0,0 +1,7 @@
|
|
1
|
+
---
|
2
|
+
SHA1:
|
3
|
+
metadata.gz: ecd9c30f38a51fee1c95bb8645ae15494812343c
|
4
|
+
data.tar.gz: 42092695de9ae9ff16a5276abbe5cf7d2e778ad4
|
5
|
+
SHA512:
|
6
|
+
metadata.gz: c06385f6d626b4487f986d73bebdb313a9860f530b9dead1794de74c42a0f9bb73779c6c918c27cb1fe43b350276aab3785ced9727228cf9282618b864fb20c6
|
7
|
+
data.tar.gz: 741917ed92b464e2b3580a3c63dd7552d7641c0457029c2031b19c7146b38d141c279c35d989d215f5df1a8f5d2dd95cdc90d73f793ffc367ad5a96cf6f4cc61
|
data/CHANGELOG
ADDED
@@ -0,0 +1,35 @@
|
|
1
|
+
* Apr 17 2008 *
|
2
|
+
* amazon_s3.yml is now passed through ERB before being passed to AWS::S3 [François Beausoleil]
|
3
|
+
|
4
|
+
* Mar 22 2008 *
|
5
|
+
* Some tweaks to support Rails 2.0 and Rails 2.1 due to ActiveSupport::Callback changes.
|
6
|
+
Thanks to http://blog.methodmissing.com/2008/1/19/edge-callback-refactorings-attachment_fu/
|
7
|
+
|
8
|
+
* Feb. 26, 2008 *
|
9
|
+
* remove breakpoint from test_helper, makes test suite crazy (at least Rails 2+) [Rob Sanheim]
|
10
|
+
* make S3 test really optional [Rob Sanheim]
|
11
|
+
|
12
|
+
* Nov 27, 2007 *
|
13
|
+
* Handle properly ImageScience thumbnails resized from a gif file [Matt Aimonetti]
|
14
|
+
* Save thumbnails file size properly when using ImageScience [Matt Aimonetti]
|
15
|
+
* fixed s3 config file loading with latest versions of Rails [Matt Aimonetti]
|
16
|
+
|
17
|
+
* April 2, 2007 *
|
18
|
+
|
19
|
+
* don't copy the #full_filename to the default #temp_paths array if it doesn't exist
|
20
|
+
* add default ID partitioning for attachments
|
21
|
+
* add #binmode call to Tempfile (note: ruby should be doing this!) [Eric Beland]
|
22
|
+
* Check for current type of :thumbnails option.
|
23
|
+
* allow customization of the S3 configuration file path with the :s3_config_path option.
|
24
|
+
* Don't try to remove thumbnails if there aren't any. Closes #3 [ben stiglitz]
|
25
|
+
|
26
|
+
* BC * (before changelog)
|
27
|
+
|
28
|
+
* add default #temp_paths entry [mattly]
|
29
|
+
* add MiniMagick support to attachment_fu [Isacc]
|
30
|
+
* update #destroy_file to clear out any empty directories too [carlivar]
|
31
|
+
* fix references to S3Backend module [Hunter Hillegas]
|
32
|
+
* make #current_data public with db_file and s3 backends [ebryn]
|
33
|
+
* oops, actually svn add the files for s3 backend. [Jeffrey Hardy]
|
34
|
+
* experimental s3 support, egad, no tests.... [Jeffrey Hardy]
|
35
|
+
* doh, fix a few bad references to ActsAsAttachment [sixty4bit]
|
data/README.md
ADDED
@@ -0,0 +1,227 @@
|
|
1
|
+
attachment-fu
|
2
|
+
=============
|
3
|
+
|
4
|
+
[![Build Status](https://travis-ci.org/zendesk/attachment_fu.png)](https://travis-ci.org/zendesk/attachment_fu)
|
5
|
+
|
6
|
+
attachment_fu is a plugin by Rick Olson (aka technoweenie <http://techno-weenie.net>) and is the successor to acts_as_attachment. To get a basic run-through of its capabilities, check out Mike Clark's tutorial <http://clarkware.com/cgi/blosxom/2007/02/24#FileUploadFu> <-- dead and gone, can view at https://web.archive.org/web/20070708115930/http://clarkware.com/cgi/blosxom/2007/02/24
|
7
|
+
|
8
|
+
|
9
|
+
attachment_fu functionality
|
10
|
+
===========================
|
11
|
+
|
12
|
+
attachment_fu facilitates file uploads in Ruby on Rails. There are a few storage options for the actual file data, but the plugin always at a minimum stores metadata for each file in the database.
|
13
|
+
|
14
|
+
There are four storage options for files uploaded through attachment_fu:
|
15
|
+
File system
|
16
|
+
Database file
|
17
|
+
Amazon S3
|
18
|
+
Rackspace (Mosso) Cloud Files
|
19
|
+
|
20
|
+
Each method of storage many options associated with it that will be covered in the following section. Something to note, however, is that the Amazon S3 storage requires you to modify config/amazon_s3.yml, the Rackspace Cloud Files storage requires you to modify config/rackspace_cloudfiles.yml, and the Database file storage requires an extra table.
|
21
|
+
|
22
|
+
|
23
|
+
attachment_fu models
|
24
|
+
====================
|
25
|
+
|
26
|
+
For all three of these storage options a table of metadata is required. This table will contain information about the file (hence the 'meta') and its location. This table has no restrictions on naming, unlike the extra table required for database storage, which must have a table name of db_files (and by convention a model of DbFile).
|
27
|
+
|
28
|
+
In the model there are two methods made available by this plugins: has_attachment and validates_as_attachment.
|
29
|
+
|
30
|
+
has_attachment(options = {})
|
31
|
+
This method accepts the options in a hash:
|
32
|
+
:content_type # Allowed content types.
|
33
|
+
# Allows all by default. Use :image to allow all standard image types.
|
34
|
+
:min_size # Minimum size allowed.
|
35
|
+
# 1 byte is the default.
|
36
|
+
:max_size # Maximum size allowed.
|
37
|
+
# 1.megabyte is the default.
|
38
|
+
:size # Range of sizes allowed.
|
39
|
+
# (1..1.megabyte) is the default. This overrides the :min_size and :max_size options.
|
40
|
+
:resize_to # Used by RMagick to resize images.
|
41
|
+
# Pass either an array of width/height, or a geometry string.
|
42
|
+
:thumbnails # Specifies a set of thumbnails to generate.
|
43
|
+
# This accepts a hash of filename suffixes and RMagick resizing options.
|
44
|
+
# This option need only be included if you want thumbnailing.
|
45
|
+
:thumbnail_class # Set which model class to use for thumbnails.
|
46
|
+
# This current attachment class is used by default.
|
47
|
+
:path_prefix # Path to store the uploaded files in.
|
48
|
+
# Uses public/#{table_name} by default for the filesystem, and just #{table_name} for the S3 and Cloud Files backend.
|
49
|
+
# Setting this sets the :storage to :file_system.
|
50
|
+
:partition # Whether to partiton files in directories like /0000/0001/image.jpg. Default is true. Only applicable to the :file_system backend.
|
51
|
+
:storage # Specifies the storage system to use..
|
52
|
+
# Defaults to :db_file. Options are :file_system, :db_file, :s3, :cloud_files, and :mogile_fs.
|
53
|
+
:cloudfront # If using S3 for storage, this option allows for serving the files via Amazon CloudFront.
|
54
|
+
# Defaults to false.
|
55
|
+
:store_name # When using multiple stores per attachment, this specifies a unique name for the store. Should be a symbol.
|
56
|
+
:processor # Sets the image processor to use for resizing of the attached image.
|
57
|
+
# Options include ImageScience, Rmagick, and MiniMagick. Default is whatever is installed.
|
58
|
+
:uuid_primary_key # If your model's primary key is a 128-bit UUID in hexadecimal format, then set this to true.
|
59
|
+
:association_options # attachment_fu automatically defines associations with thumbnails with has_many and belongs_to. If there are any additional options that you want to pass to these methods, then specify them here.
|
60
|
+
|
61
|
+
|
62
|
+
Examples:
|
63
|
+
has_attachment :max_size => 1.kilobyte
|
64
|
+
has_attachment :size => 1.megabyte..2.megabytes
|
65
|
+
has_attachment :content_type => 'application/pdf'
|
66
|
+
has_attachment :content_type => ['application/pdf', 'application/msword', 'text/plain']
|
67
|
+
has_attachment :content_type => :image, :resize_to => [50,50]
|
68
|
+
has_attachment :content_type => ['application/pdf', :image], :resize_to => 'x50'
|
69
|
+
has_attachment :thumbnails => { :thumb => [50, 50], :geometry => 'x50' }
|
70
|
+
has_attachment :storage => :file_system, :path_prefix => 'public/files'
|
71
|
+
has_attachment :storage => :file_system, :path_prefix => 'public/files',
|
72
|
+
:content_type => :image, :resize_to => [50,50], :partition => false
|
73
|
+
has_attachment :storage => :file_system, :path_prefix => 'public/files',
|
74
|
+
:thumbnails => { :thumb => [50, 50], :geometry => 'x50' }
|
75
|
+
has_attachment :storage => :s3
|
76
|
+
has_attachment :store => :s3, :cloudfront => true
|
77
|
+
has_attachment :storage => :cloud_files
|
78
|
+
# (multiple data stores )
|
79
|
+
has_attachment :store_name => :fs, :storage => :file_system
|
80
|
+
has_attachment :store_name => :s3, :storage => :s3
|
81
|
+
|
82
|
+
validates_as_attachment
|
83
|
+
This method prevents files outside of the valid range (:min_size to :max_size, or the :size range) from being saved. It does not however, halt the upload of such files. They will be uploaded into memory regardless of size before validation.
|
84
|
+
|
85
|
+
Example:
|
86
|
+
validates_as_attachment
|
87
|
+
|
88
|
+
|
89
|
+
attachment_fu migrations
|
90
|
+
========================
|
91
|
+
|
92
|
+
Fields for attachment_fu metadata tables...
|
93
|
+
in general:
|
94
|
+
size, :integer # file size in bytes
|
95
|
+
content_type, :string # mime type, ex: application/mp3
|
96
|
+
filename, :string # sanitized filename
|
97
|
+
that reference multiple attachment stores:
|
98
|
+
stores, :string
|
99
|
+
that reference images:
|
100
|
+
height, :integer # in pixels
|
101
|
+
width, :integer # in pixels
|
102
|
+
that reference images that will be thumbnailed:
|
103
|
+
parent_id, :integer # id of parent image (on the same table, a self-referencing foreign-key).
|
104
|
+
# Only populated if the current object is a thumbnail.
|
105
|
+
thumbnail, :string # the 'type' of thumbnail this attachment record describes.
|
106
|
+
# Only populated if the current object is a thumbnail.
|
107
|
+
# Usage:
|
108
|
+
# [ In Model 'Avatar' ]
|
109
|
+
# has_attachment :content_type => :image,
|
110
|
+
# :storage => :file_system,
|
111
|
+
# :max_size => 500.kilobytes,
|
112
|
+
# :resize_to => '320x200>',
|
113
|
+
# :thumbnails => { :small => '10x10>',
|
114
|
+
# :thumb => '100x100>' }
|
115
|
+
# [ Elsewhere ]
|
116
|
+
# @user.avatar.thumbnails.first.thumbnail #=> 'small'
|
117
|
+
md5, :string # md5 hash for the attachment
|
118
|
+
that reference files stored in the database (:db_file):
|
119
|
+
db_file_id, :integer # id of the file in the database (foreign key)
|
120
|
+
|
121
|
+
Field for attachment_fu db_files table:
|
122
|
+
data, :binary # binary file data, for use in database file storage
|
123
|
+
|
124
|
+
|
125
|
+
attachment_fu views
|
126
|
+
===================
|
127
|
+
|
128
|
+
There are two main views tasks that will be directly affected by attachment_fu: upload forms and displaying uploaded images.
|
129
|
+
|
130
|
+
There are two parts of the upload form that differ from typical usage.
|
131
|
+
1. Include ':multipart => true' in the html options of the form_for tag.
|
132
|
+
Example:
|
133
|
+
<% form_for(:attachment_metadata, :url => { :action => "create" }, :html => { :multipart => true }) do |form| %>
|
134
|
+
|
135
|
+
2. Use the file_field helper with :uploaded_data as the field name.
|
136
|
+
Example:
|
137
|
+
<%= form.file_field :uploaded_data %>
|
138
|
+
|
139
|
+
Displaying uploaded images is made easy by the public_filename method of the ActiveRecord attachment objects using file system, s3, and Cloud Files storage.
|
140
|
+
|
141
|
+
public_filename(thumbnail = nil)
|
142
|
+
Returns the public path to the file. If a thumbnail prefix is specified it will return the public file path to the corresponding thumbnail.
|
143
|
+
Examples:
|
144
|
+
attachment_obj.public_filename #=> /attachments/2/file.jpg
|
145
|
+
attachment_obj.public_filename(:thumb) #=> /attachments/2/file_thumb.jpg
|
146
|
+
attachment_obj.public_filename(:small) #=> /attachments/2/file_small.jpg
|
147
|
+
|
148
|
+
When serving files from database storage, doing more than simply downloading the file is beyond the scope of this document.
|
149
|
+
|
150
|
+
|
151
|
+
attachment_fu controllers
|
152
|
+
=========================
|
153
|
+
|
154
|
+
There are two considerations to take into account when using attachment_fu in controllers.
|
155
|
+
|
156
|
+
The first is when the files have no publicly accessible path and need to be downloaded through an action.
|
157
|
+
|
158
|
+
Example:
|
159
|
+
def readme
|
160
|
+
send_file '/path/to/readme.txt', :type => 'plain/text', :disposition => 'inline'
|
161
|
+
end
|
162
|
+
|
163
|
+
See the possible values for send_file for reference.
|
164
|
+
|
165
|
+
|
166
|
+
The second is when saving the file when submitted from a form.
|
167
|
+
Example in view:
|
168
|
+
<%= form.file_field :attachable, :uploaded_data %>
|
169
|
+
|
170
|
+
Example in controller:
|
171
|
+
def create
|
172
|
+
@attachable_file = AttachmentMetadataModel.new(params[:attachable])
|
173
|
+
if @attachable_file.save
|
174
|
+
flash[:notice] = 'Attachment was successfully created.'
|
175
|
+
redirect_to attachable_url(@attachable_file)
|
176
|
+
else
|
177
|
+
render :action => :new
|
178
|
+
end
|
179
|
+
end
|
180
|
+
|
181
|
+
attachement_fu scripting
|
182
|
+
====================================
|
183
|
+
|
184
|
+
You may wish to import a large number of images or attachments.
|
185
|
+
The following example shows how to upload a file from a script.
|
186
|
+
|
187
|
+
#!/usr/bin/env ./script/runner
|
188
|
+
|
189
|
+
# required to use ActionController::TestUploadedFile
|
190
|
+
require 'action_controller'
|
191
|
+
require 'action_controller/test_process.rb'
|
192
|
+
|
193
|
+
path = "./public/images/x.jpg"
|
194
|
+
|
195
|
+
# mimetype is a string like "image/jpeg". One way to get the mimetype for a given file on a UNIX system
|
196
|
+
# mimetype = `file -ib #{path}`.gsub(/\n/,"")
|
197
|
+
|
198
|
+
mimetype = "image/jpeg"
|
199
|
+
|
200
|
+
# This will "upload" the file at path and create the new model.
|
201
|
+
@attachable = AttachmentMetadataModel.new(:uploaded_data => ActionController::TestUploadedFile.new(path, mimetype))
|
202
|
+
@attachable.save
|
203
|
+
|
204
|
+
Testing
|
205
|
+
======
|
206
|
+
|
207
|
+
S3 Test
|
208
|
+
-----
|
209
|
+
|
210
|
+
Instructions for running the s3 tests.
|
211
|
+
|
212
|
+
1. ensure mysql is installed, and the 'root' user has no password
|
213
|
+
2. create the database named `attachment_fu_plugin_test`
|
214
|
+
3. copy amazon_s3.yml.tpl to test/amazon_s3.yml
|
215
|
+
4. update test/amazon_s3.yml with your bucket name and s3 credentials
|
216
|
+
5. run the test script `test/backends/remote/s3_test.rb`
|
217
|
+
|
218
|
+
You can run all the test, or just `rake test` but most of the tests are disabled unless you setup their dependencies and config files.
|
219
|
+
|
220
|
+
|
221
|
+
CloudFiles tests
|
222
|
+
------
|
223
|
+
|
224
|
+
ensure that your test container is set 'public'
|
225
|
+
|
226
|
+
|
227
|
+
|
@@ -0,0 +1,8 @@
|
|
1
|
+
require 'tempfile'
|
2
|
+
require 'active_record'
|
3
|
+
require 'technoweenie/attachment_fu'
|
4
|
+
require 'technoweenie/attachment_fu/geometry'
|
5
|
+
|
6
|
+
ActiveRecord::Base.send(:extend, Technoweenie::AttachmentFu::ActMethods)
|
7
|
+
Technoweenie::AttachmentFu.tempfile_path = ATTACHMENT_FU_TEMPFILE_PATH if Object.const_defined?(:ATTACHMENT_FU_TEMPFILE_PATH)
|
8
|
+
FileUtils.mkdir_p Technoweenie::AttachmentFu.tempfile_path
|
@@ -0,0 +1,771 @@
|
|
1
|
+
require 'digest/md5'
|
2
|
+
require 'active_support'
|
3
|
+
require 'active_support/core_ext'
|
4
|
+
require 'timeout'
|
5
|
+
|
6
|
+
module Technoweenie # :nodoc:
|
7
|
+
module AttachmentFu # :nodoc:
|
8
|
+
module Backends
|
9
|
+
autoload :BackendDelegator, 'technoweenie/attachment_fu/backends/backend_delegator'
|
10
|
+
autoload :CloudFileBackend, 'technoweenie/attachment_fu/backends/cloud_file_backend'
|
11
|
+
autoload :DbFileBackend, 'technoweenie/attachment_fu/backends/db_file_backend'
|
12
|
+
autoload :FileSystemBackend, 'technoweenie/attachment_fu/backends/file_system_backend'
|
13
|
+
autoload :MogileFsBackend, 'technoweenie/attachment_fu/backends/mogile_fs_backend'
|
14
|
+
autoload :S3Backend, 'technoweenie/attachment_fu/backends/s3_backend'
|
15
|
+
end
|
16
|
+
|
17
|
+
module Processors
|
18
|
+
autoload :CoreImageProcessor, 'technoweenie/attachment_fu/processors/core_image_processor'
|
19
|
+
autoload :Gd2Processor, 'technoweenie/attachment_fu/processors/gd2_processor'
|
20
|
+
autoload :ImageScienceProcessor, 'technoweenie/attachment_fu/processors/image_science_processor'
|
21
|
+
autoload :MiniMagickProcessor, 'technoweenie/attachment_fu/processors/mini_magick_processor'
|
22
|
+
autoload :RmagickProcessor, 'technoweenie/attachment_fu/processors/rmagick_processor'
|
23
|
+
end
|
24
|
+
|
25
|
+
@@default_processors = %w(ImageScience Rmagick MiniMagick Gd2 CoreImage)
|
26
|
+
@@tempfile_path = Rails.root.join('tmp/attachment_fu').to_s
|
27
|
+
@@content_types = [
|
28
|
+
'image/jpeg',
|
29
|
+
'image/pjpeg',
|
30
|
+
'image/jpg',
|
31
|
+
'image/gif',
|
32
|
+
'image/png',
|
33
|
+
'image/x-png',
|
34
|
+
'image/jpg',
|
35
|
+
'image/x-ms-bmp',
|
36
|
+
'image/bmp',
|
37
|
+
'image/x-bmp',
|
38
|
+
'image/x-bitmap',
|
39
|
+
'image/x-xbitmap',
|
40
|
+
'image/x-win-bitmap',
|
41
|
+
'image/x-windows-bmp',
|
42
|
+
'image/ms-bmp',
|
43
|
+
'application/bmp',
|
44
|
+
'application/x-bmp',
|
45
|
+
'application/x-win-bitmap',
|
46
|
+
'application/preview',
|
47
|
+
'image/jp_',
|
48
|
+
'application/jpg',
|
49
|
+
'application/x-jpg',
|
50
|
+
'image/pipeg',
|
51
|
+
'image/vnd.swiftview-jpeg',
|
52
|
+
'image/x-xbitmap',
|
53
|
+
'application/png',
|
54
|
+
'application/x-png',
|
55
|
+
'image/gi_',
|
56
|
+
'image/x-citrix-pjpeg'
|
57
|
+
]
|
58
|
+
@@mime_type_detector = ->(file_data) { file_data.content_type }
|
59
|
+
mattr_reader :content_types, :tempfile_path, :default_processors, :mime_type_detector
|
60
|
+
mattr_writer :tempfile_path
|
61
|
+
|
62
|
+
class ThumbnailError < StandardError; end
|
63
|
+
class AttachmentError < StandardError; end
|
64
|
+
|
65
|
+
module ActMethods
|
66
|
+
# Options:
|
67
|
+
# * <tt>:content_type</tt> - Allowed content types. Allows all by default. Use :image to allow all standard image types.
|
68
|
+
# * <tt>:min_size</tt> - Minimum size allowed. 1 byte is the default.
|
69
|
+
# * <tt>:max_size</tt> - Maximum size allowed. 1.megabyte is the default.
|
70
|
+
# * <tt>:size</tt> - Range of sizes allowed. (1..1.megabyte) is the default. This overrides the :min_size and :max_size options.
|
71
|
+
# * <tt>:resize_to</tt> - Used by RMagick to resize images. Pass either an array of width/height, or a geometry string.
|
72
|
+
# * <tt>:thumbnails</tt> - Specifies a set of thumbnails to generate. This accepts a hash of filename suffixes and RMagick resizing options.
|
73
|
+
# * <tt>:thumbnail_class</tt> - Set what class to use for thumbnails. This attachment class is used by default.
|
74
|
+
# * <tt>:path_prefix</tt> - path to store the uploaded files. Uses public/#{table_name} by default for the filesystem, and just #{table_name}
|
75
|
+
# for the S3 backend. Setting this sets the :storage to :file_system.
|
76
|
+
|
77
|
+
# * <tt>:storage</tt> - Use :file_system to specify the attachment data is stored with the file system. Defaults to :db_system.
|
78
|
+
# * <tt>:cloundfront</tt> - Set to true if you are using S3 storage and want to serve the files through CloudFront. You will need to
|
79
|
+
# set a distribution domain in the amazon_s3.yml config file. Defaults to false
|
80
|
+
# * <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
|
81
|
+
# different buckets for different models. An example setting would be :image_bucket and the you would need to define the name of the corresponding
|
82
|
+
# bucket in the amazon_s3.yml file.
|
83
|
+
|
84
|
+
# * <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.
|
85
|
+
#
|
86
|
+
# Examples:
|
87
|
+
# has_attachment :max_size => 1.kilobyte
|
88
|
+
# has_attachment :size => 1.megabyte..2.megabytes
|
89
|
+
# has_attachment :content_type => 'application/pdf'
|
90
|
+
# has_attachment :content_type => ['application/pdf', 'application/msword', 'text/plain']
|
91
|
+
# has_attachment :content_type => :image, :resize_to => [50,50]
|
92
|
+
# has_attachment :content_type => ['application/pdf', :image], :resize_to => 'x50'
|
93
|
+
# has_attachment :thumbnails => { :thumb => [50, 50], :geometry => 'x50' }
|
94
|
+
# has_attachment :storage => :file_system, :path_prefix => 'public/files'
|
95
|
+
# has_attachment :storage => :file_system, :path_prefix => 'public/files',
|
96
|
+
# :content_type => :image, :resize_to => [50,50]
|
97
|
+
# has_attachment :storage => :file_system, :path_prefix => 'public/files',
|
98
|
+
# :thumbnails => { :thumb => [50, 50], :geometry => 'x50' }
|
99
|
+
# has_attachment :storage => :s3
|
100
|
+
# has_attachment :storage_key => 'store',
|
101
|
+
# :backends => { 's3' => { :storage => :s3, :path_prefix => 'foo', :max_size => 5.kilobyte, :default => true },
|
102
|
+
# 'local1' => { :storage => :file_system, :path_prefix => 'data/public' } }
|
103
|
+
|
104
|
+
def has_attachment(options = {})
|
105
|
+
# this allows you to redefine the acts' options for each subclass, however
|
106
|
+
options[:min_size] ||= 1
|
107
|
+
options[:max_size] ||= 1.megabyte
|
108
|
+
options[:size] ||= (options[:min_size]..options[:max_size])
|
109
|
+
options[:thumbnails] ||= {}
|
110
|
+
options[:thumbnail_class] ||= self
|
111
|
+
options[:s3_access] ||= :private
|
112
|
+
options[:cloudfront] ||= false
|
113
|
+
options[:store_name] ||= :default
|
114
|
+
options[:content_type] = [options[:content_type]].flatten.collect! { |t| t == :image ? Technoweenie::AttachmentFu.content_types : t }.flatten unless options[:content_type].nil?
|
115
|
+
|
116
|
+
unless options[:thumbnails].is_a?(Hash)
|
117
|
+
raise ArgumentError, ":thumbnails option should be a hash: e.g. :thumbnails => { :foo => '50x50' }"
|
118
|
+
end
|
119
|
+
|
120
|
+
extend ClassMethods unless (class << self; included_modules; end).include?(ClassMethods)
|
121
|
+
include InstanceMethods unless included_modules.include?(InstanceMethods)
|
122
|
+
|
123
|
+
attr_accessor :thumbnail_resize_options
|
124
|
+
|
125
|
+
parent_options = attachment_options || {}
|
126
|
+
|
127
|
+
self.attachment_options = options
|
128
|
+
# doing these shenanigans so that #attachment_options is available to processors and backends
|
129
|
+
|
130
|
+
|
131
|
+
attachment_options[:storage] ||= (attachment_options[:file_system_path] || attachment_options[:path_prefix]) ? :file_system : :db_file
|
132
|
+
attachment_options[:storage] ||= parent_options[:storage]
|
133
|
+
attachment_options[:path_prefix] ||= attachment_options[:file_system_path]
|
134
|
+
if attachment_options[:path_prefix].nil?
|
135
|
+
attachment_options[:path_prefix] = case attachment_options[:storage]
|
136
|
+
when :s3 then table_name
|
137
|
+
when :cloud_files then table_name
|
138
|
+
when :mogile_fs then table_name
|
139
|
+
else File.join("public", table_name)
|
140
|
+
end
|
141
|
+
end
|
142
|
+
attachment_options[:path_prefix] = attachment_options[:path_prefix][1..-1] if options[:path_prefix].first == '/'
|
143
|
+
|
144
|
+
association_options = { :foreign_key => 'parent_id' }
|
145
|
+
if attachment_options[:association_options]
|
146
|
+
association_options.merge!(attachment_options[:association_options])
|
147
|
+
end
|
148
|
+
with_options(association_options) do |m|
|
149
|
+
m.has_many :thumbnails, :class_name => "::#{attachment_options[:thumbnail_class]}"
|
150
|
+
m.belongs_to :parent, :class_name => "::#{base_class}" unless options[:thumbnails].empty?
|
151
|
+
end
|
152
|
+
|
153
|
+
self.attachment_backends ||= {}
|
154
|
+
storage_klass_name = case options[:storage]
|
155
|
+
when :mogile_fs
|
156
|
+
"MogileFS"
|
157
|
+
else
|
158
|
+
options[:storage].to_s.classify
|
159
|
+
end
|
160
|
+
|
161
|
+
storage_klass = Technoweenie::AttachmentFu::Backends.const_get("#{storage_klass_name}Backend")
|
162
|
+
|
163
|
+
self.attachment_backends[attachment_options[:store_name]] = {:klass => storage_klass, :options => attachment_options}
|
164
|
+
storage_klass.included_in_base(self)
|
165
|
+
|
166
|
+
# support syntax-sugar of "a = Attachment.new ; a.s3.authenticated_s3_url" for accessing store-specific stuff
|
167
|
+
self.class_eval "def #{attachment_options[:store_name]}; get_storage_delegator(:#{attachment_options[:store_name]}); end"
|
168
|
+
|
169
|
+
case attachment_options[:processor]
|
170
|
+
when :none, nil
|
171
|
+
processors = Technoweenie::AttachmentFu.default_processors.dup
|
172
|
+
begin
|
173
|
+
if processors.any?
|
174
|
+
attachment_options[:processor] = processors.first
|
175
|
+
processor_mod = Technoweenie::AttachmentFu::Processors.const_get("#{attachment_options[:processor].to_s.classify}Processor")
|
176
|
+
include processor_mod unless included_modules.include?(processor_mod)
|
177
|
+
end
|
178
|
+
rescue Object, Exception
|
179
|
+
raise unless load_related_exception?($!)
|
180
|
+
|
181
|
+
processors.shift
|
182
|
+
retry
|
183
|
+
end
|
184
|
+
else
|
185
|
+
begin
|
186
|
+
processor_mod = Technoweenie::AttachmentFu::Processors.const_get("#{attachment_options[:processor].to_s.classify}Processor")
|
187
|
+
include processor_mod unless included_modules.include?(processor_mod)
|
188
|
+
rescue Object, Exception
|
189
|
+
raise unless load_related_exception?($!)
|
190
|
+
|
191
|
+
puts "Problems loading #{options[:processor]}Processor: #{$!}"
|
192
|
+
end
|
193
|
+
end unless parent_options[:processor] # Don't let child override processor
|
194
|
+
end
|
195
|
+
|
196
|
+
# helper method for has_attachment, for if you want to set up stuff from a yaml file
|
197
|
+
def setup_attachment_fu(extra_opts = {}, config_filename = nil)
|
198
|
+
config_file ||= Rails.root.join("config/attachments.yml").to_s
|
199
|
+
raise "No attachment_fu configuration found, tried #{config_file}" unless File.exist?(config_file)
|
200
|
+
|
201
|
+
att_opts = YAML.load(ERB.new(File.read(config_file)).result)[Rails.env]
|
202
|
+
raise "No attachment_fu configuration found for environment #{Rails.env}" unless att_opts
|
203
|
+
|
204
|
+
arr = att_opts[self.name.tableize] || att_opts[:default]
|
205
|
+
|
206
|
+
raise "No attachment_fu configuration found for table #{self.name.tableize}" unless arr
|
207
|
+
arr = [arr] if arr.is_a?(Hash) # both flavors!
|
208
|
+
arr.each do |val|
|
209
|
+
options = val.symbolize_keys.merge(extra_opts)
|
210
|
+
|
211
|
+
options[:thumbnails] = options[:thumbnails].symbolize_keys if options[:thumbnails]
|
212
|
+
[:store_name, :storage].each { |k|
|
213
|
+
options[k] = options.delete(k).to_sym if options[k]
|
214
|
+
}
|
215
|
+
|
216
|
+
has_attachment options
|
217
|
+
end
|
218
|
+
end
|
219
|
+
|
220
|
+
|
221
|
+
def load_related_exception?(e) #:nodoc: implementation specific
|
222
|
+
case
|
223
|
+
when e.kind_of?(LoadError), e.kind_of?(MissingSourceFile), $!.class.name == "CompilationError"
|
224
|
+
# We can't rescue CompilationError directly, as it is part of the RubyInline library.
|
225
|
+
# We must instead rescue RuntimeError, and check the class' name.
|
226
|
+
true
|
227
|
+
else
|
228
|
+
false
|
229
|
+
end
|
230
|
+
end
|
231
|
+
private :load_related_exception?
|
232
|
+
end
|
233
|
+
|
234
|
+
|
235
|
+
module ClassMethods
|
236
|
+
delegate :content_types, :to => Technoweenie::AttachmentFu
|
237
|
+
|
238
|
+
# Performs common validations for attachment models.
|
239
|
+
def validates_as_attachment
|
240
|
+
validates_presence_of :size, :content_type, :filename
|
241
|
+
validate :attachment_attributes_valid?
|
242
|
+
end
|
243
|
+
|
244
|
+
# Returns true or false if the given content type is recognized as an image.
|
245
|
+
def image?(content_type)
|
246
|
+
content_types.include?(content_type)
|
247
|
+
end
|
248
|
+
|
249
|
+
def self.extended(base)
|
250
|
+
base.class_attribute :attachment_options
|
251
|
+
base.class_attribute :attachment_backends
|
252
|
+
base.before_destroy :destroy_thumbnails
|
253
|
+
base.before_update :rename_files
|
254
|
+
base.before_validation :set_size_from_temp_path
|
255
|
+
base.before_validation :process_attachment, :process_attachment_moves
|
256
|
+
base.before_validation :generate_md5, :if => Proc.new {|a| a.respond_to?(:md5) && a.new_record?}
|
257
|
+
base.after_save :after_process_attachment
|
258
|
+
base.after_destroy :destroy_files
|
259
|
+
end
|
260
|
+
|
261
|
+
# Get the thumbnail class, which is the current attachment class by default.
|
262
|
+
# Configure this with the :thumbnail_class option.
|
263
|
+
def thumbnail_class
|
264
|
+
attachment_options[:thumbnail_class] = attachment_options[:thumbnail_class].constantize unless attachment_options[:thumbnail_class].is_a?(Class)
|
265
|
+
attachment_options[:thumbnail_class]
|
266
|
+
end
|
267
|
+
|
268
|
+
def new_tempfile(file)
|
269
|
+
basename, ext = [File.basename(file), File.extname(file)]
|
270
|
+
|
271
|
+
Tempfile.new([basename, ext], Technoweenie::AttachmentFu.tempfile_path)
|
272
|
+
end
|
273
|
+
|
274
|
+
|
275
|
+
# Copies the given file path to a new tempfile, returning the closed tempfile.
|
276
|
+
def copy_to_temp_file(file, temp_base_name)
|
277
|
+
tmp = new_tempfile(temp_base_name)
|
278
|
+
tmp.close
|
279
|
+
FileUtils.cp file, tmp.path
|
280
|
+
tmp
|
281
|
+
end
|
282
|
+
|
283
|
+
# Writes the given data to a new tempfile, returning the closed tempfile.
|
284
|
+
def write_to_temp_file(data, temp_base_name)
|
285
|
+
tmp = new_tempfile(temp_base_name)
|
286
|
+
tmp.binmode
|
287
|
+
tmp.write data
|
288
|
+
tmp.close
|
289
|
+
tmp
|
290
|
+
end
|
291
|
+
end
|
292
|
+
|
293
|
+
module InstanceMethods
|
294
|
+
# Checks whether the attachment's content type is an image content type
|
295
|
+
def image?
|
296
|
+
self.class.image?(content_type)
|
297
|
+
end
|
298
|
+
|
299
|
+
# Returns true/false if an attachment is thumbnailable. A thumbnailable attachment has an image content type and the parent_id attribute.
|
300
|
+
def thumbnailable?
|
301
|
+
image? && respond_to?(:parent_id) && parent_id.nil?
|
302
|
+
end
|
303
|
+
|
304
|
+
# Returns the class used to create new thumbnails for this attachment.
|
305
|
+
def thumbnail_class
|
306
|
+
self.class.thumbnail_class
|
307
|
+
end
|
308
|
+
|
309
|
+
# Gets the thumbnail name for a filename. 'foo.jpg' becomes 'foo_thumbnail.jpg'
|
310
|
+
def thumbnail_name_for(thumbnail = nil)
|
311
|
+
return filename if thumbnail.blank?
|
312
|
+
ext = nil
|
313
|
+
basename = filename.gsub /\.\w+$/ do |s|
|
314
|
+
ext = s; ''
|
315
|
+
end
|
316
|
+
# ImageScience doesn't create gif thumbnails, only pngs
|
317
|
+
ext.sub!(/gif$/, 'png') if attachment_options[:processor] == "ImageScience"
|
318
|
+
"#{basename}_#{thumbnail}#{ext}"
|
319
|
+
end
|
320
|
+
|
321
|
+
# Creates or updates the thumbnail for the current attachment.
|
322
|
+
def create_or_update_thumbnail(temp_file, file_name_suffix, *size)
|
323
|
+
thumbnailable? || raise(ThumbnailError.new("Can't create a thumbnail if the content type is not an image or there is no parent_id column"))
|
324
|
+
thumb = find_or_initialize_thumbnail(file_name_suffix)
|
325
|
+
|
326
|
+
thumb.temp_paths.unshift temp_file
|
327
|
+
thumb.send(:'attributes=', {
|
328
|
+
:content_type => content_type,
|
329
|
+
:filename => thumbnail_name_for(file_name_suffix),
|
330
|
+
:thumbnail_resize_options => size
|
331
|
+
})
|
332
|
+
thumb.stores = stores
|
333
|
+
thumb.save!
|
334
|
+
|
335
|
+
thumb
|
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
|
+
with_each_store(true) do |store|
|
346
|
+
store.notify_rename if store.respond_to?(:notify_rename)
|
347
|
+
end
|
348
|
+
|
349
|
+
write_attribute :filename, sanitize_filename(new_name) if has_attribute?(:filename)
|
350
|
+
end
|
351
|
+
|
352
|
+
# Returns the width/height in a suitable format for the image_tag helper: (100x100)
|
353
|
+
def image_size
|
354
|
+
[width.to_s, height.to_s] * 'x'
|
355
|
+
end
|
356
|
+
|
357
|
+
# Returns true if the attachment data will be written to the storage system on the next save
|
358
|
+
def save_attachment?
|
359
|
+
File.file?(temp_path.to_s)
|
360
|
+
end
|
361
|
+
|
362
|
+
# nil placeholder in case this field is used in a form.
|
363
|
+
def uploaded_data() nil; end
|
364
|
+
|
365
|
+
# This method handles the uploaded file object. If you set the field name to uploaded_data, you don't need
|
366
|
+
# any special code in your controller.
|
367
|
+
#
|
368
|
+
# <% form_for :attachment, :html => { :multipart => true } do |f| -%>
|
369
|
+
# <p><%= f.file_field :uploaded_data %></p>
|
370
|
+
# <p><%= submit_tag :Save %>
|
371
|
+
# <% end -%>
|
372
|
+
#
|
373
|
+
# @attachment = AttachmentTest.create! params[:attachment]
|
374
|
+
#
|
375
|
+
# TODO: Allow it to work with Merb tempfiles too.
|
376
|
+
def uploaded_data=(file_data)
|
377
|
+
if file_data.respond_to?(:content_type)
|
378
|
+
return nil if file_data.size == 0
|
379
|
+
self.content_type = Technoweenie::AttachmentFu.mime_type_detector.call(file_data)
|
380
|
+
self.filename = file_data.original_filename if respond_to?(:filename)
|
381
|
+
else
|
382
|
+
return nil if file_data.blank? || file_data['size'] == 0
|
383
|
+
self.content_type = file_data['content_type']
|
384
|
+
self.filename = file_data['filename']
|
385
|
+
file_data = file_data['tempfile']
|
386
|
+
end
|
387
|
+
if file_data.is_a?(StringIO)
|
388
|
+
file_data.rewind
|
389
|
+
set_temp_data file_data.read
|
390
|
+
else
|
391
|
+
self.temp_paths.unshift file_data
|
392
|
+
end
|
393
|
+
end
|
394
|
+
|
395
|
+
# Gets the latest temp path from the collection of temp paths. While working with an attachment,
|
396
|
+
# multiple Tempfile objects may be created for various processing purposes (resizing, for example).
|
397
|
+
# An array of all the tempfile objects is stored so that the Tempfile instance is held on to until
|
398
|
+
# it's not needed anymore. The collection is cleared after saving the attachment.
|
399
|
+
def temp_path
|
400
|
+
p = temp_paths.first
|
401
|
+
p.respond_to?(:path) ? p.path : p
|
402
|
+
end
|
403
|
+
|
404
|
+
# Gets an array of the currently used temp paths. Defaults to a copy of #full_filename.
|
405
|
+
def temp_paths
|
406
|
+
@temp_paths ||= []
|
407
|
+
end
|
408
|
+
|
409
|
+
# Gets the data from the latest temp file. This will read the file into memory.
|
410
|
+
def temp_data
|
411
|
+
save_attachment? ? File.read(temp_path) : nil
|
412
|
+
end
|
413
|
+
|
414
|
+
# Writes the given data to a Tempfile and adds it to the collection of temp files.
|
415
|
+
def set_temp_data(data)
|
416
|
+
temp_paths.unshift write_to_temp_file data unless data.nil?
|
417
|
+
end
|
418
|
+
|
419
|
+
# Copies the given file to a randomly named Tempfile.
|
420
|
+
def copy_to_temp_file(file)
|
421
|
+
self.class.copy_to_temp_file file, random_tempfile_filename
|
422
|
+
end
|
423
|
+
|
424
|
+
# Writes the given file to a randomly named Tempfile.
|
425
|
+
def write_to_temp_file(data)
|
426
|
+
self.class.write_to_temp_file data, random_tempfile_filename
|
427
|
+
end
|
428
|
+
|
429
|
+
# supports backwards compat -- we pretend that methods are mixed in. Might screw with someone using respond_to? though.
|
430
|
+
ONE_STORE_METHODS = [:full_filename, :current_data, :base_path, :attachment_path_id, :partitioned_path, :cloudfront_url,
|
431
|
+
:authenticated_s3_url, :s3_config, :cloudfiles_config, :container_name, :cloudfiles_url, :cloudfiles_storage_url, :cloudfiles_authtoken, :s3_url, :bucket_name, :s3_protocol, :s3_hostname, :s3_port_string]
|
432
|
+
|
433
|
+
ONE_STORE_METHODS.each do |method|
|
434
|
+
eval("def #{method}(*args) ; on_one_store(:#{method}, nil, *args) ; end")
|
435
|
+
end
|
436
|
+
|
437
|
+
def supports_multiple_stores?
|
438
|
+
has_attribute?(:stores)
|
439
|
+
end
|
440
|
+
|
441
|
+
def to_store_list(input)
|
442
|
+
return [] if input.nil?
|
443
|
+
input = input.split(",") if input.is_a?(String)
|
444
|
+
input.flatten! if input.is_a?(Array)
|
445
|
+
input.map(&:to_sym)
|
446
|
+
end
|
447
|
+
|
448
|
+
private :to_store_list
|
449
|
+
|
450
|
+
def stores
|
451
|
+
if !supports_multiple_stores?
|
452
|
+
[self.class.attachment_backends.keys.first]
|
453
|
+
else
|
454
|
+
stores = read_attribute(:stores) || ''
|
455
|
+
to_store_list(stores)
|
456
|
+
end
|
457
|
+
end
|
458
|
+
|
459
|
+
def old_stores
|
460
|
+
if new_record?
|
461
|
+
[]
|
462
|
+
elsif !supports_multiple_stores?
|
463
|
+
[self.class.attachment_backends.keys.first]
|
464
|
+
else
|
465
|
+
to_store_list(stores_was)
|
466
|
+
end
|
467
|
+
end
|
468
|
+
|
469
|
+
def stored_in?(backend)
|
470
|
+
old_stores.include?(backend)
|
471
|
+
end
|
472
|
+
|
473
|
+
def stores=(*input)
|
474
|
+
if supports_multiple_stores?
|
475
|
+
write_attribute(:stores, input.flatten.uniq.map(&:to_s).join(','))
|
476
|
+
end
|
477
|
+
end
|
478
|
+
|
479
|
+
# Creates a temp file with the current data.
|
480
|
+
def create_temp_file
|
481
|
+
write_to_temp_file current_data
|
482
|
+
end
|
483
|
+
|
484
|
+
# Allows you to work with a processed representation (RMagick, ImageScience, etc) of the attachment in a block.
|
485
|
+
#
|
486
|
+
# @attachment.with_image do |img|
|
487
|
+
# self.data = img.thumbnail(100, 100).to_blob
|
488
|
+
# end
|
489
|
+
#
|
490
|
+
def with_image(&block)
|
491
|
+
self.class.with_image(temp_path, &block)
|
492
|
+
end
|
493
|
+
|
494
|
+
def save_without_processing
|
495
|
+
without_processing { save }
|
496
|
+
end
|
497
|
+
|
498
|
+
def save_without_processing!
|
499
|
+
without_processing { save! }
|
500
|
+
end
|
501
|
+
|
502
|
+
def generate_md5
|
503
|
+
self.md5 = md5_from_file(temp_path || create_temp_file) rescue nil
|
504
|
+
end
|
505
|
+
|
506
|
+
def logger
|
507
|
+
@logger ||= begin
|
508
|
+
if Object.const_defined?(:Rails)
|
509
|
+
Rails.logger
|
510
|
+
else
|
511
|
+
Logger.new($stdout)
|
512
|
+
end
|
513
|
+
end
|
514
|
+
end
|
515
|
+
|
516
|
+
protected
|
517
|
+
|
518
|
+
# Generates a unique filename for a Tempfile.
|
519
|
+
def random_tempfile_filename
|
520
|
+
"#{rand Time.now.to_i}#{filename || 'attachment'}"
|
521
|
+
end
|
522
|
+
|
523
|
+
def sanitize_filename(filename)
|
524
|
+
return unless filename
|
525
|
+
|
526
|
+
name = filename.strip
|
527
|
+
|
528
|
+
# NOTE: File.basename doesn't work right with Windows paths on Unix
|
529
|
+
# get only the filename, not the whole path
|
530
|
+
name.gsub! /^.*(\\|\/)/, ''
|
531
|
+
|
532
|
+
# Finally, replace all non alphanumeric, underscore or periods with underscore
|
533
|
+
name.gsub! /[^A-Za-z0-9\.\-]/, '_'
|
534
|
+
|
535
|
+
name
|
536
|
+
end
|
537
|
+
|
538
|
+
# before_validation callback.
|
539
|
+
def set_size_from_temp_path
|
540
|
+
self.size = File.size(temp_path) if save_attachment?
|
541
|
+
end
|
542
|
+
|
543
|
+
# validates the size and content_type attributes according to the current model's options
|
544
|
+
def attachment_attributes_valid?
|
545
|
+
[:size, :content_type].each do |attr_name|
|
546
|
+
enum = attachment_options[attr_name]
|
547
|
+
enum_str = case enum
|
548
|
+
when Array
|
549
|
+
enum.join(",")
|
550
|
+
else
|
551
|
+
enum.to_s
|
552
|
+
end
|
553
|
+
|
554
|
+
msg = if Object.const_defined?(:I18n)
|
555
|
+
I18n.translate("activerecord.errors.messages.inclusion_with_attribute", :attribute => I18n.translate("activerecord.attributes.attachments.#{attr_name}"))
|
556
|
+
else
|
557
|
+
ActiveRecord::Errors.default_error_messages[:inclusion]
|
558
|
+
end
|
559
|
+
|
560
|
+
unless enum.nil? || enum.include?(send(attr_name))
|
561
|
+
errors.add attr_name, msg + " (#{enum_str})"
|
562
|
+
end
|
563
|
+
end
|
564
|
+
end
|
565
|
+
|
566
|
+
# Initializes a new thumbnail with the given suffix.
|
567
|
+
def find_or_initialize_thumbnail(file_name_suffix)
|
568
|
+
attributes = {thumbnail: file_name_suffix.to_s}
|
569
|
+
attributes[:parent_id] = id if respond_to?(:parent_id)
|
570
|
+
thumbnail_class.where(attributes).first || thumbnail_class.new(attributes)
|
571
|
+
end
|
572
|
+
|
573
|
+
def has_attachment_processor?
|
574
|
+
self.respond_to?(:_process_attachment, true)
|
575
|
+
end
|
576
|
+
|
577
|
+
def without_processing
|
578
|
+
begin
|
579
|
+
@no_processing = true
|
580
|
+
yield
|
581
|
+
ensure
|
582
|
+
@no_processing = false
|
583
|
+
end
|
584
|
+
end
|
585
|
+
|
586
|
+
def process_attachment
|
587
|
+
@saved_attachment ||= save_attachment?
|
588
|
+
if @saved_attachment && has_attachment_processor? && !@no_processing
|
589
|
+
self._process_attachment
|
590
|
+
end
|
591
|
+
true
|
592
|
+
end
|
593
|
+
|
594
|
+
# if we're not given a specific storage engine, we'll grab one that the attachment actually has, starting with the default.
|
595
|
+
def get_storage_delegator(backend)
|
596
|
+
@attachment_fu_delegators ||= {}
|
597
|
+
|
598
|
+
backends = self.class.attachment_backends
|
599
|
+
if backend.nil?
|
600
|
+
if backends.size == 1
|
601
|
+
backend = backends.keys.first
|
602
|
+
else
|
603
|
+
list = backends.find_all { |a|
|
604
|
+
stored_in?(a[0])
|
605
|
+
}
|
606
|
+
backend = list.map { |k, v| v[:options][:default] ? k : nil }.compact.first
|
607
|
+
if !backend
|
608
|
+
backend = list[0][0]
|
609
|
+
end
|
610
|
+
end
|
611
|
+
end
|
612
|
+
|
613
|
+
hash = backends[backend]
|
614
|
+
@attachment_fu_delegators[backend] ||= hash[:klass].new(self, hash[:options])
|
615
|
+
@attachment_fu_delegators[backend]
|
616
|
+
end
|
617
|
+
|
618
|
+
def on_one_store(method, backend, *args)
|
619
|
+
delegator = nil
|
620
|
+
if backend
|
621
|
+
delegator = get_storage_delegator(backend)
|
622
|
+
else
|
623
|
+
with_each_store(true) { |store|
|
624
|
+
# using methods.include instead of respond_to? because the delegation has already screwed up respond_to?
|
625
|
+
# checking both the string (ruby 1.8) and the symbol (ruby 1.9)
|
626
|
+
if store.methods.include?(method.to_s) || store.methods.include?(method.to_sym)
|
627
|
+
delegator = store
|
628
|
+
break
|
629
|
+
end
|
630
|
+
}
|
631
|
+
end
|
632
|
+
|
633
|
+
raise NoMethodError, "No stores responded to \"#{method}\"" if delegator.nil?
|
634
|
+
delegator.send(method, *args)
|
635
|
+
end
|
636
|
+
|
637
|
+
def with_each_store(only_active=false)
|
638
|
+
self.class.attachment_backends.each do |k, v|
|
639
|
+
if !only_active || stored_in?(k)
|
640
|
+
yield get_storage_delegator(k)
|
641
|
+
end
|
642
|
+
end
|
643
|
+
end
|
644
|
+
|
645
|
+
def process_attachment_moves
|
646
|
+
return true if !supports_multiple_stores?
|
647
|
+
if new_record?
|
648
|
+
@saved_attachment = true
|
649
|
+
self.stores = default_attachment_stores
|
650
|
+
raise "Please configure one attachment store as :default" if stores.empty?
|
651
|
+
true
|
652
|
+
else
|
653
|
+
# update -- if we've set uploaded_data =, we don't need to run these checks
|
654
|
+
return true if @saved_attachment
|
655
|
+
|
656
|
+
if Set.new(old_stores) != Set.new(stores)
|
657
|
+
data = current_data
|
658
|
+
set_temp_data(data) if data
|
659
|
+
@saved_attachment = true
|
660
|
+
end
|
661
|
+
end
|
662
|
+
end
|
663
|
+
|
664
|
+
def default_attachment_stores
|
665
|
+
backends = self.class.attachment_backends
|
666
|
+
if backends.size == 1
|
667
|
+
[backends.keys.first]
|
668
|
+
else
|
669
|
+
backends.map { |k, v| v[:options][:default] ? k : nil }.compact
|
670
|
+
end
|
671
|
+
end
|
672
|
+
|
673
|
+
|
674
|
+
def was_stored_in?(store, name)
|
675
|
+
stores_was && to_store_list(stores_was).include?(name) && store.current_data
|
676
|
+
end
|
677
|
+
|
678
|
+
def handle_saving_exception(name)
|
679
|
+
new_stores = stores.reject { |s| s == name.to_sym }.join(",")
|
680
|
+
write_attribute(:stores, new_stores)
|
681
|
+
self.class.update_all({:stores => new_stores}, ["id = ?", self.id])
|
682
|
+
end
|
683
|
+
|
684
|
+
def save_with_timeout(store)
|
685
|
+
Timeout.timeout(store.attachment_options[:timeout]) do
|
686
|
+
store.save_to_storage
|
687
|
+
end
|
688
|
+
end
|
689
|
+
|
690
|
+
def store_name(store)
|
691
|
+
store.attachment_options[:store_name]
|
692
|
+
end
|
693
|
+
|
694
|
+
def save_to_storage(store, name)
|
695
|
+
begin
|
696
|
+
save_with_timeout(store)
|
697
|
+
name
|
698
|
+
rescue Exception => e
|
699
|
+
logger.error("Exception saving #{self.filename} to #{name}: #{e.inspect}")
|
700
|
+
handle_saving_exception(name)
|
701
|
+
end
|
702
|
+
end
|
703
|
+
|
704
|
+
def process_stores
|
705
|
+
with_each_store do |store|
|
706
|
+
name = store_name(store)
|
707
|
+
|
708
|
+
if stores.include?(name)
|
709
|
+
save_to_storage(store, name)
|
710
|
+
else
|
711
|
+
store.destroy_file if was_stored_in?(store, name)
|
712
|
+
end
|
713
|
+
end
|
714
|
+
stores
|
715
|
+
end
|
716
|
+
|
717
|
+
# Cleans up after processing. Thumbnails are created, the attachment is stored to the backend, and the temp_paths are cleared.
|
718
|
+
def after_process_attachment
|
719
|
+
if @saved_attachment
|
720
|
+
set_size_from_temp_path
|
721
|
+
|
722
|
+
if has_attachment_processor? && thumbnailable? && !attachment_options[:thumbnails].blank? && parent_id.nil? && !@no_processing
|
723
|
+
temp_file = temp_path || create_temp_file
|
724
|
+
attachment_options[:thumbnails].each { |suffix, size| create_or_update_thumbnail(temp_file, suffix, *size) }
|
725
|
+
end
|
726
|
+
|
727
|
+
process_stores
|
728
|
+
|
729
|
+
@temp_paths.clear
|
730
|
+
@saved_attachment = nil
|
731
|
+
@old_attachment_stores = nil
|
732
|
+
@target_attachment_stores = nil
|
733
|
+
end
|
734
|
+
end
|
735
|
+
|
736
|
+
def destroy_files
|
737
|
+
with_each_store(true) do |store|
|
738
|
+
store.destroy_file
|
739
|
+
end
|
740
|
+
end
|
741
|
+
|
742
|
+
def rename_files
|
743
|
+
with_each_store(true) do |store|
|
744
|
+
store.rename_file
|
745
|
+
end
|
746
|
+
end
|
747
|
+
|
748
|
+
# Resizes the given processed img object with either the attachment resize options or the thumbnail resize options.
|
749
|
+
def resize_image_or_thumbnail!(img)
|
750
|
+
if (!respond_to?(:parent_id) || parent_id.nil?) && attachment_options[:resize_to] # parent image
|
751
|
+
resize_image(img, attachment_options[:resize_to])
|
752
|
+
elsif thumbnail_resize_options # thumbnail
|
753
|
+
resize_image(img, thumbnail_resize_options)
|
754
|
+
end
|
755
|
+
end
|
756
|
+
|
757
|
+
# Removes the thumbnails for the attachment, if it has any
|
758
|
+
def destroy_thumbnails
|
759
|
+
self.thumbnails.each { |thumbnail| thumbnail.destroy } if thumbnailable?
|
760
|
+
end
|
761
|
+
|
762
|
+
def md5_from_file(path)
|
763
|
+
digest = Digest::MD5.new
|
764
|
+
File.open(path) do |file|
|
765
|
+
digest << file.read(4096) until file.eof?
|
766
|
+
end
|
767
|
+
digest.hexdigest
|
768
|
+
end
|
769
|
+
end
|
770
|
+
end
|
771
|
+
end
|