ncri_attachment_fu 0.1.8

Sign up to get free protection for your applications and to get access to all the features.
Files changed (28) hide show
  1. data/CHANGELOG +35 -0
  2. data/LICENSE +20 -0
  3. data/README +193 -0
  4. data/amazon_s3.yml.tpl +17 -0
  5. data/lib/attachment_fu.rb +17 -0
  6. data/lib/geometry.rb +93 -0
  7. data/lib/technoweenie/attachment_fu.rb +533 -0
  8. data/lib/technoweenie/attachment_fu/backends.rb +4 -0
  9. data/lib/technoweenie/attachment_fu/backends/cloud_file_backend.rb +211 -0
  10. data/lib/technoweenie/attachment_fu/backends/db_file_backend.rb +39 -0
  11. data/lib/technoweenie/attachment_fu/backends/file_system_backend.rb +126 -0
  12. data/lib/technoweenie/attachment_fu/backends/s3_backend.rb +394 -0
  13. data/lib/technoweenie/attachment_fu/processors.rb +1 -0
  14. data/lib/technoweenie/attachment_fu/processors/core_image_processor.rb +59 -0
  15. data/lib/technoweenie/attachment_fu/processors/gd2_processor.rb +54 -0
  16. data/lib/technoweenie/attachment_fu/processors/image_science_processor.rb +61 -0
  17. data/lib/technoweenie/attachment_fu/processors/mini_magick_processor.rb +132 -0
  18. data/lib/technoweenie/attachment_fu/processors/rmagick_processor.rb +57 -0
  19. data/rackspace_cloudfiles.yml.tpl +14 -0
  20. data/rails/install.rb +7 -0
  21. data/vendor/red_artisan/core_image/filters/color.rb +27 -0
  22. data/vendor/red_artisan/core_image/filters/effects.rb +31 -0
  23. data/vendor/red_artisan/core_image/filters/perspective.rb +25 -0
  24. data/vendor/red_artisan/core_image/filters/quality.rb +25 -0
  25. data/vendor/red_artisan/core_image/filters/scale.rb +47 -0
  26. data/vendor/red_artisan/core_image/filters/watermark.rb +32 -0
  27. data/vendor/red_artisan/core_image/processor.rb +123 -0
  28. metadata +75 -0
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/LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ Copyright (c) 2009 rick olson
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README ADDED
@@ -0,0 +1,193 @@
1
+ attachment-fu
2
+ =============
3
+
4
+ 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>.
5
+
6
+
7
+ attachment_fu functionality
8
+ ===========================
9
+
10
+ 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.
11
+
12
+ There are four storage options for files uploaded through attachment_fu:
13
+ File system
14
+ Database file
15
+ Amazon S3
16
+ Rackspace (Mosso) Cloud Files
17
+
18
+ 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.
19
+
20
+
21
+ attachment_fu models
22
+ ====================
23
+
24
+ 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).
25
+
26
+ In the model there are two methods made available by this plugins: has_attachment and validates_as_attachment.
27
+
28
+ has_attachment(options = {})
29
+ This method accepts the options in a hash:
30
+ :content_type # Allowed content types.
31
+ # Allows all by default. Use :image to allow all standard image types.
32
+ :min_size # Minimum size allowed.
33
+ # 1 byte is the default.
34
+ :max_size # Maximum size allowed.
35
+ # 1.megabyte is the default.
36
+ :size # Range of sizes allowed.
37
+ # (1..1.megabyte) is the default. This overrides the :min_size and :max_size options.
38
+ :resize_to # Used by RMagick to resize images.
39
+ # Pass either an array of width/height, or a geometry string.
40
+ :thumbnails # Specifies a set of thumbnails to generate.
41
+ # This accepts a hash of filename suffixes and RMagick resizing options.
42
+ # This option need only be included if you want thumbnailing.
43
+ :thumbnail_class # Set which model class to use for thumbnails.
44
+ # This current attachment class is used by default.
45
+ :path_prefix # Path to store the uploaded files in.
46
+ # Uses public/#{table_name} by default for the filesystem, and just #{table_name} for the S3 and Cloud Files backend.
47
+ # Setting this sets the :storage to :file_system.
48
+ :partition # Whether to partiton files in directories like /0000/0001/image.jpg. Default is true. Only applicable to the :file_system backend.
49
+ :storage # Specifies the storage system to use..
50
+ # Defaults to :db_file. Options are :file_system, :db_file, :s3, and :cloud_files.
51
+ :cloudfront # If using S3 for storage, this option allows for serving the files via Amazon CloudFront.
52
+ # Defaults to false.
53
+ :processor # Sets the image processor to use for resizing of the attached image.
54
+ # Options include ImageScience, Rmagick, and MiniMagick. Default is whatever is installed.
55
+ :uuid_primary_key # If your model's primary key is a 128-bit UUID in hexadecimal format, then set this to true.
56
+ :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.
57
+
58
+
59
+ Examples:
60
+ has_attachment :max_size => 1.kilobyte
61
+ has_attachment :size => 1.megabyte..2.megabytes
62
+ has_attachment :content_type => 'application/pdf'
63
+ has_attachment :content_type => ['application/pdf', 'application/msword', 'text/plain']
64
+ has_attachment :content_type => :image, :resize_to => [50,50]
65
+ has_attachment :content_type => ['application/pdf', :image], :resize_to => 'x50'
66
+ has_attachment :thumbnails => { :thumb => [50, 50], :geometry => 'x50' }
67
+ has_attachment :storage => :file_system, :path_prefix => 'public/files'
68
+ has_attachment :storage => :file_system, :path_prefix => 'public/files',
69
+ :content_type => :image, :resize_to => [50,50], :partition => false
70
+ has_attachment :storage => :file_system, :path_prefix => 'public/files',
71
+ :thumbnails => { :thumb => [50, 50], :geometry => 'x50' }
72
+ has_attachment :storage => :s3
73
+ has_attachment :store => :s3, :cloudfront => true
74
+ has_attachment :storage => :cloud_files
75
+
76
+ validates_as_attachment
77
+ 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.
78
+
79
+ Example:
80
+ validates_as_attachment
81
+
82
+
83
+ attachment_fu migrations
84
+ ========================
85
+
86
+ Fields for attachment_fu metadata tables...
87
+ in general:
88
+ size, :integer # file size in bytes
89
+ content_type, :string # mime type, ex: application/mp3
90
+ filename, :string # sanitized filename
91
+ that reference images:
92
+ height, :integer # in pixels
93
+ width, :integer # in pixels
94
+ that reference images that will be thumbnailed:
95
+ parent_id, :integer # id of parent image (on the same table, a self-referencing foreign-key).
96
+ # Only populated if the current object is a thumbnail.
97
+ thumbnail, :string # the 'type' of thumbnail this attachment record describes.
98
+ # Only populated if the current object is a thumbnail.
99
+ # Usage:
100
+ # [ In Model 'Avatar' ]
101
+ # has_attachment :content_type => :image,
102
+ # :storage => :file_system,
103
+ # :max_size => 500.kilobytes,
104
+ # :resize_to => '320x200>',
105
+ # :thumbnails => { :small => '10x10>',
106
+ # :thumb => '100x100>' }
107
+ # [ Elsewhere ]
108
+ # @user.avatar.thumbnails.first.thumbnail #=> 'small'
109
+ that reference files stored in the database (:db_file):
110
+ db_file_id, :integer # id of the file in the database (foreign key)
111
+
112
+ Field for attachment_fu db_files table:
113
+ data, :binary # binary file data, for use in database file storage
114
+
115
+
116
+ attachment_fu views
117
+ ===================
118
+
119
+ There are two main views tasks that will be directly affected by attachment_fu: upload forms and displaying uploaded images.
120
+
121
+ There are two parts of the upload form that differ from typical usage.
122
+ 1. Include ':multipart => true' in the html options of the form_for tag.
123
+ Example:
124
+ <% form_for(:attachment_metadata, :url => { :action => "create" }, :html => { :multipart => true }) do |form| %>
125
+
126
+ 2. Use the file_field helper with :uploaded_data as the field name.
127
+ Example:
128
+ <%= form.file_field :uploaded_data %>
129
+
130
+ Displaying uploaded images is made easy by the public_filename method of the ActiveRecord attachment objects using file system, s3, and Cloud Files storage.
131
+
132
+ public_filename(thumbnail = nil)
133
+ Returns the public path to the file. If a thumbnail prefix is specified it will return the public file path to the corresponding thumbnail.
134
+ Examples:
135
+ attachment_obj.public_filename #=> /attachments/2/file.jpg
136
+ attachment_obj.public_filename(:thumb) #=> /attachments/2/file_thumb.jpg
137
+ attachment_obj.public_filename(:small) #=> /attachments/2/file_small.jpg
138
+
139
+ When serving files from database storage, doing more than simply downloading the file is beyond the scope of this document.
140
+
141
+
142
+ attachment_fu controllers
143
+ =========================
144
+
145
+ There are two considerations to take into account when using attachment_fu in controllers.
146
+
147
+ The first is when the files have no publicly accessible path and need to be downloaded through an action.
148
+
149
+ Example:
150
+ def readme
151
+ send_file '/path/to/readme.txt', :type => 'plain/text', :disposition => 'inline'
152
+ end
153
+
154
+ See the possible values for send_file for reference.
155
+
156
+
157
+ The second is when saving the file when submitted from a form.
158
+ Example in view:
159
+ <%= form.file_field :attachable, :uploaded_data %>
160
+
161
+ Example in controller:
162
+ def create
163
+ @attachable_file = AttachmentMetadataModel.new(params[:attachable])
164
+ if @attachable_file.save
165
+ flash[:notice] = 'Attachment was successfully created.'
166
+ redirect_to attachable_url(@attachable_file)
167
+ else
168
+ render :action => :new
169
+ end
170
+ end
171
+
172
+ attachement_fu scripting
173
+ ====================================
174
+
175
+ You may wish to import a large number of images or attachments.
176
+ The following example shows how to upload a file from a script.
177
+
178
+ #!/usr/bin/env ./script/runner
179
+
180
+ # required to use ActionController::TestUploadedFile
181
+ require 'action_controller'
182
+ require 'action_controller/test_process.rb'
183
+
184
+ path = "./public/images/x.jpg"
185
+
186
+ # mimetype is a string like "image/jpeg". One way to get the mimetype for a given file on a UNIX system
187
+ # mimetype = `file -ib #{path}`.gsub(/\n/,"")
188
+
189
+ mimetype = "image/jpeg"
190
+
191
+ # This will "upload" the file at path and create the new model.
192
+ @attachable = AttachmentMetadataModel.new(:uploaded_data => ActionController::TestUploadedFile.new(path, mimetype))
193
+ @attachable.save
data/amazon_s3.yml.tpl ADDED
@@ -0,0 +1,17 @@
1
+ development:
2
+ bucket_name: appname_development
3
+ access_key_id:
4
+ secret_access_key:
5
+ distribution_domain: XXXX.cloudfront.net
6
+
7
+ test:
8
+ bucket_name: appname_test
9
+ access_key_id:
10
+ secret_access_key:
11
+ distribution_domain: XXXX.cloudfront.net
12
+
13
+ production:
14
+ bucket_name: appname
15
+ access_key_id:
16
+ secret_access_key:
17
+ distribution_domain: XXXX.cloudfront.net
@@ -0,0 +1,17 @@
1
+ #require 'tempfile'
2
+ #
3
+ #Tempfile.class_eval do
4
+ # # overwrite so tempfiles use the extension of the basename. important for rmagick and image science
5
+ # def make_tmpname(basename, n)
6
+ # ext = nil
7
+ # sprintf("%s%d-%d%s", basename.to_s.gsub(/\.\w+$/) { |s| ext = s; '' }, $$, (n || Time.now.tv_usec), ext)
8
+ # end
9
+ #end
10
+
11
+ require 'geometry'
12
+ require 'technoweenie/attachment_fu'
13
+ ActiveRecord::Base.send(:extend, Technoweenie::AttachmentFu::ActMethods)
14
+ Technoweenie::AttachmentFu.tempfile_path = ATTACHMENT_FU_TEMPFILE_PATH if Object.const_defined?(:ATTACHMENT_FU_TEMPFILE_PATH)
15
+ FileUtils.mkdir_p Technoweenie::AttachmentFu.tempfile_path
16
+
17
+ $:.unshift(File.dirname(__FILE__) + '/vendor')
data/lib/geometry.rb ADDED
@@ -0,0 +1,93 @@
1
+ # This Geometry class was yanked from RMagick. However, it lets ImageMagick handle the actual change_geometry.
2
+ # Use #new_dimensions_for to get new dimensons
3
+ # Used so I can use spiffy RMagick geometry strings with ImageScience
4
+ class Geometry
5
+ # ! and @ are removed until support for them is added
6
+ FLAGS = ['', '%', '<', '>']#, '!', '@']
7
+ RFLAGS = { '%' => :percent,
8
+ '!' => :aspect,
9
+ '<' => :>,
10
+ '>' => :<,
11
+ '@' => :area }
12
+
13
+ attr_accessor :width, :height, :x, :y, :flag
14
+
15
+ def initialize(width=nil, height=nil, x=nil, y=nil, flag=nil)
16
+ # Support floating-point width and height arguments so Geometry
17
+ # objects can be used to specify Image#density= arguments.
18
+ raise ArgumentError, "width must be >= 0: #{width}" if width < 0
19
+ raise ArgumentError, "height must be >= 0: #{height}" if height < 0
20
+ @width = width.to_f
21
+ @height = height.to_f
22
+ @x = x.to_i
23
+ @y = y.to_i
24
+ @flag = flag
25
+ end
26
+
27
+ # Construct an object from a geometry string
28
+ RE = /\A(\d*)(?:x(\d+)?)?([-+]\d+)?([-+]\d+)?([%!<>@]?)\Z/
29
+
30
+ def self.from_s(str)
31
+ raise(ArgumentError, "no geometry string specified") unless str
32
+
33
+ if m = RE.match(str)
34
+ new(m[1].to_i, m[2].to_i, m[3].to_i, m[4].to_i, RFLAGS[m[5]])
35
+ else
36
+ raise ArgumentError, "invalid geometry format"
37
+ end
38
+ end
39
+
40
+ # Convert object to a geometry string
41
+ def to_s
42
+ str = ''
43
+ str << "%g" % @width if @width > 0
44
+ str << 'x' if (@width > 0 || @height > 0)
45
+ str << "%g" % @height if @height > 0
46
+ str << "%+d%+d" % [@x, @y] if (@x != 0 || @y != 0)
47
+ str << FLAGS[@flag.to_i]
48
+ end
49
+
50
+ # attempts to get new dimensions for the current geometry string given these old dimensions.
51
+ # This doesn't implement the aspect flag (!) or the area flag (@). PDI
52
+ def new_dimensions_for(orig_width, orig_height)
53
+ new_width = orig_width
54
+ new_height = orig_height
55
+
56
+ case @flag
57
+ when :percent
58
+ scale_x = @width.zero? ? 100 : @width
59
+ scale_y = @height.zero? ? @width : @height
60
+ new_width = scale_x.to_f * (orig_width.to_f / 100.0)
61
+ new_height = scale_y.to_f * (orig_height.to_f / 100.0)
62
+ when :<, :>, nil
63
+ scale_factor =
64
+ if new_width.zero? || new_height.zero?
65
+ 1.0
66
+ else
67
+ if @width.nonzero? && @height.nonzero?
68
+ [@width.to_f / new_width.to_f, @height.to_f / new_height.to_f].min
69
+ else
70
+ @width.nonzero? ? (@width.to_f / new_width.to_f) : (@height.to_f / new_height.to_f)
71
+ end
72
+ end
73
+ new_width = scale_factor * new_width.to_f
74
+ new_height = scale_factor * new_height.to_f
75
+ new_width = orig_width if @flag && orig_width.send(@flag, new_width)
76
+ new_height = orig_height if @flag && orig_height.send(@flag, new_height)
77
+ end
78
+
79
+ [new_width, new_height].collect! { |v| [v.round, 1].max }
80
+ end
81
+ end
82
+
83
+ class Array
84
+ # allows you to get new dimensions for the current array of dimensions with a given geometry string
85
+ #
86
+ # [50, 64] / '40>' # => [40, 51]
87
+ def /(geometry)
88
+ raise ArgumentError, "Only works with a [width, height] pair" if size != 2
89
+ raise ArgumentError, "Must pass a valid geometry string or object" unless geometry.is_a?(String) || geometry.is_a?(Geometry)
90
+ geometry = Geometry.from_s(geometry) if geometry.is_a?(String)
91
+ geometry.new_dimensions_for first, last
92
+ end
93
+ end
@@ -0,0 +1,533 @@
1
+ require 'technoweenie/attachment_fu/backends'
2
+ require 'technoweenie/attachment_fu/processors'
3
+
4
+ module Technoweenie # :nodoc:
5
+ module AttachmentFu # :nodoc:
6
+ @@default_processors = %w(image_science rmagick mini_magick gd2 core_image)
7
+ @@tempfile_path = File.join(Rails.root.to_s, 'tmp', 'attachment_fu')
8
+ @@content_types = [
9
+ 'image/jpeg',
10
+ 'image/pjpeg',
11
+ 'image/jpg',
12
+ 'image/gif',
13
+ 'image/png',
14
+ 'image/x-png',
15
+ 'image/jpg',
16
+ 'image/x-ms-bmp',
17
+ 'image/bmp',
18
+ 'image/x-bmp',
19
+ 'image/x-bitmap',
20
+ 'image/x-xbitmap',
21
+ 'image/x-win-bitmap',
22
+ 'image/x-windows-bmp',
23
+ 'image/ms-bmp',
24
+ 'application/bmp',
25
+ 'application/x-bmp',
26
+ 'application/x-win-bitmap',
27
+ 'application/preview',
28
+ 'image/jp_',
29
+ 'application/jpg',
30
+ 'application/x-jpg',
31
+ 'image/pipeg',
32
+ 'image/vnd.swiftview-jpeg',
33
+ 'image/x-xbitmap',
34
+ 'application/png',
35
+ 'application/x-png',
36
+ 'image/gi_',
37
+ 'image/x-citrix-pjpeg'
38
+ ]
39
+ mattr_reader :content_types, :tempfile_path, :default_processors
40
+ mattr_writer :tempfile_path
41
+
42
+ class ThumbnailError < StandardError; end
43
+ class AttachmentError < StandardError; end
44
+
45
+ module ActMethods
46
+ # Options:
47
+ # * <tt>:content_type</tt> - Allowed content types. Allows all by default. Use :image to allow all standard image types.
48
+ # * <tt>:min_size</tt> - Minimum size allowed. 1 byte is the default.
49
+ # * <tt>:max_size</tt> - Maximum size allowed. 1.megabyte is the default.
50
+ # * <tt>:size</tt> - Range of sizes allowed. (1..1.megabyte) is the default. This overrides the :min_size and :max_size options.
51
+ # * <tt>:resize_to</tt> - Used by RMagick to resize images. Pass either an array of width/height, or a geometry string.
52
+ # * <tt>:thumbnails</tt> - Specifies a set of thumbnails to generate. This accepts a hash of filename suffixes and RMagick resizing options.
53
+ # * <tt>:thumbnail_class</tt> - Set what class to use for thumbnails. This attachment class is used by default.
54
+ # * <tt>:path_prefix</tt> - path to store the uploaded files. Uses public/#{table_name} by default for the filesystem, and just #{table_name}
55
+ # for the S3 backend. Setting this sets the :storage to :file_system.
56
+
57
+ # * <tt>:storage</tt> - Use :file_system to specify the attachment data is stored with the file system. Defaults to :db_system.
58
+ # * <tt>:cloundfront</tt> - Set to true if you are using S3 storage and want to serve the files through CloudFront. You will need to
59
+ # set a distribution domain in the amazon_s3.yml config file. Defaults to false
60
+ # * <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
61
+ # different buckets for different models. An example setting would be :image_bucket and the you would need to define the name of the corresponding
62
+ # bucket in the amazon_s3.yml file.
63
+
64
+ # * <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.
65
+ #
66
+ # Examples:
67
+ # has_attachment :max_size => 1.kilobyte
68
+ # has_attachment :size => 1.megabyte..2.megabytes
69
+ # has_attachment :content_type => 'application/pdf'
70
+ # has_attachment :content_type => ['application/pdf', 'application/msword', 'text/plain']
71
+ # has_attachment :content_type => :image, :resize_to => [50,50]
72
+ # has_attachment :content_type => ['application/pdf', :image], :resize_to => 'x50'
73
+ # has_attachment :thumbnails => { :thumb => [50, 50], :geometry => 'x50' }
74
+ # has_attachment :storage => :file_system, :path_prefix => 'public/files'
75
+ # has_attachment :storage => :file_system, :path_prefix => 'public/files',
76
+ # :content_type => :image, :resize_to => [50,50]
77
+ # has_attachment :storage => :file_system, :path_prefix => 'public/files',
78
+ # :thumbnails => { :thumb => [50, 50], :geometry => 'x50' }
79
+ # has_attachment :storage => :s3
80
+ def has_attachment(options = {})
81
+ # this allows you to redefine the acts' options for each subclass, however
82
+ options[:min_size] ||= 1
83
+ options[:max_size] ||= 1.megabyte
84
+ options[:size] ||= (options[:min_size]..options[:max_size])
85
+ options[:thumbnails] ||= {}
86
+ options[:thumbnail_class] ||= self
87
+ options[:s3_access] ||= :public_read
88
+ options[:cloudfront] ||= false
89
+ options[:content_type] = [options[:content_type]].flatten.collect! { |t| t == :image ? Technoweenie::AttachmentFu.content_types : t }.flatten unless options[:content_type].nil?
90
+
91
+ unless options[:thumbnails].is_a?(Hash)
92
+ raise ArgumentError, ":thumbnails option should be a hash: e.g. :thumbnails => { :foo => '50x50' }"
93
+ end
94
+
95
+ extend ClassMethods unless (class << self; included_modules; end).include?(ClassMethods)
96
+ include InstanceMethods unless included_modules.include?(InstanceMethods)
97
+
98
+ parent_options = attachment_options || {}
99
+ # doing these shenanigans so that #attachment_options is available to processors and backends
100
+ self.attachment_options = options
101
+
102
+ attr_accessor :thumbnail_resize_options
103
+
104
+ attachment_options[:storage] ||= (attachment_options[:file_system_path] || attachment_options[:path_prefix]) ? :file_system : :db_file
105
+ attachment_options[:storage] ||= parent_options[:storage]
106
+ attachment_options[:path_prefix] ||= attachment_options[:file_system_path]
107
+ if attachment_options[:path_prefix].nil?
108
+ attachment_options[:path_prefix] = case attachment_options[:storage]
109
+ when :s3 then table_name
110
+ when :cloud_files then table_name
111
+ else File.join("public", table_name)
112
+ end
113
+ end
114
+ attachment_options[:path_prefix] = attachment_options[:path_prefix][1..-1] if options[:path_prefix].first == '/'
115
+
116
+ association_options = { :foreign_key => 'parent_id' }
117
+ if attachment_options[:association_options]
118
+ association_options.merge!(attachment_options[:association_options])
119
+ end
120
+ with_options(association_options) do |m|
121
+ m.has_many :thumbnails, :class_name => "::#{attachment_options[:thumbnail_class]}"
122
+ m.belongs_to :parent, :class_name => "::#{base_class}" unless options[:thumbnails].empty?
123
+ end
124
+
125
+ storage_mod = Technoweenie::AttachmentFu::Backends.const_get("#{options[:storage].to_s.classify}Backend")
126
+ include storage_mod unless included_modules.include?(storage_mod)
127
+
128
+ case attachment_options[:processor]
129
+ when :none, nil
130
+ processors = Technoweenie::AttachmentFu.default_processors.dup
131
+ begin
132
+ if processors.any?
133
+ attachment_options[:processor] = processors.first
134
+ require "#{attachment_options[:processor].to_s.underscore}_processor" rescue
135
+ require("technoweenie/attachment_fu/processors/#{attachment_options[:processor].to_s.underscore}_processor") rescue
136
+ processor_mod = Technoweenie::AttachmentFu::Processors.const_get("#{attachment_options[:processor].to_s.classify}Processor")
137
+ include processor_mod unless included_modules.include?(processor_mod)
138
+ end
139
+ rescue Object, Exception
140
+ raise unless load_related_exception?($!)
141
+
142
+ processors.shift
143
+ retry
144
+ end
145
+ else
146
+ begin
147
+ require "#{attachment_options[:processor].to_s.underscore}_processor"
148
+ processor_mod = Technoweenie::AttachmentFu::Processors.const_get("#{attachment_options[:processor].to_s.classify}Processor")
149
+ include processor_mod unless included_modules.include?(processor_mod)
150
+ rescue Object, Exception
151
+ raise unless load_related_exception?($!)
152
+
153
+ puts "Problems loading #{options[:processor]}Processor: #{$!}"
154
+ end
155
+ end unless parent_options[:processor] # Don't let child override processor
156
+ end
157
+
158
+ def load_related_exception?(e) #:nodoc: implementation specific
159
+ case
160
+ when e.kind_of?(LoadError), e.kind_of?(MissingSourceFile), $!.class.name == "CompilationError"
161
+ # We can't rescue CompilationError directly, as it is part of the RubyInline library.
162
+ # We must instead rescue RuntimeError, and check the class' name.
163
+ true
164
+ else
165
+ false
166
+ end
167
+ end
168
+ private :load_related_exception?
169
+ end
170
+
171
+ module ClassMethods
172
+ delegate :content_types, :to => Technoweenie::AttachmentFu
173
+
174
+ # Performs common validations for attachment models.
175
+ def validates_as_attachment
176
+ validates_presence_of :size, :content_type, :filename
177
+ validate :attachment_attributes_valid?
178
+ end
179
+
180
+ # Returns true or false if the given content type is recognized as an image.
181
+ def image?(content_type)
182
+ content_types.include?(content_type)
183
+ end
184
+
185
+ def self.extended(base)
186
+ base.class_attribute :attachment_options
187
+ base.before_destroy :destroy_thumbnails
188
+ base.before_validation :set_size_from_temp_path
189
+ base.after_save :after_process_attachment
190
+ base.after_destroy :destroy_file
191
+ base.after_validation :process_attachment
192
+ if defined?(::ActiveSupport::Callbacks)
193
+ base.define_callbacks :resize, :kind => :after
194
+ base.define_callbacks :thumbnail_saved, :kind => :before
195
+ end
196
+ end
197
+
198
+ unless defined?(::ActiveSupport::Callbacks)
199
+ # Callback after an image has been resized.
200
+ #
201
+ # class Foo < ActiveRecord::Base
202
+ # acts_as_attachment
203
+ # after_resize do |record, img|
204
+ # record.aspect_ratio = img.columns.to_f / img.rows.to_f
205
+ # end
206
+ # end
207
+ def after_resize(&block)
208
+ write_inheritable_array(:after_resize, [block])
209
+ end
210
+
211
+ # Callback before a thumbnail is saved. Use this to pass any necessary extra attributes that may be required.
212
+ #
213
+ # class Foo < ActiveRecord::Base
214
+ # acts_as_attachment
215
+ # before_thumbnail_saved do |thumbnail|
216
+ # record = thumbnail.parent
217
+ # ...
218
+ # end
219
+ # end
220
+ def before_thumbnail_saved(&block)
221
+ write_inheritable_array(:before_thumbnail_saved, [block])
222
+ end
223
+ end
224
+
225
+ # Get the thumbnail class, which is the current attachment class by default.
226
+ # Configure this with the :thumbnail_class option.
227
+ def thumbnail_class
228
+ attachment_options[:thumbnail_class] = attachment_options[:thumbnail_class].constantize unless attachment_options[:thumbnail_class].is_a?(Class)
229
+ attachment_options[:thumbnail_class]
230
+ end
231
+
232
+ # Copies the given file path to a new tempfile, returning the closed tempfile.
233
+ def copy_to_temp_file(file, temp_base_name)
234
+ Tempfile.new(temp_base_name, Technoweenie::AttachmentFu.tempfile_path).tap do |tmp|
235
+ tmp.close
236
+ FileUtils.cp file, tmp.path
237
+ end
238
+ end
239
+
240
+ # Writes the given data to a new tempfile, returning the closed tempfile.
241
+ def write_to_temp_file(data, temp_base_name)
242
+ Tempfile.new(temp_base_name, Technoweenie::AttachmentFu.tempfile_path).tap do |tmp|
243
+ tmp.binmode
244
+ tmp.write data
245
+ tmp.close
246
+ end
247
+ end
248
+ end
249
+
250
+ module InstanceMethods
251
+ def self.included(base)
252
+ if base.respond_to?(:define_callbacks)
253
+ base.class_eval do
254
+ define_callbacks :resize, :attachment_saved, :kind => :after
255
+ define_callbacks :thumbnail_saved, :kind => :before
256
+ end
257
+ end
258
+ end
259
+
260
+ # Checks whether the attachment's content type is an image content type
261
+ def image?
262
+ self.class.image?(content_type)
263
+ end
264
+
265
+ # Returns true/false if an attachment is thumbnailable. A thumbnailable attachment has an image content type and the parent_id attribute.
266
+ def thumbnailable?
267
+ image? && respond_to?(:parent_id) && parent_id.nil?
268
+ end
269
+
270
+ # Returns the class used to create new thumbnails for this attachment.
271
+ def thumbnail_class
272
+ self.class.thumbnail_class
273
+ end
274
+
275
+ # Gets the thumbnail name for a filename. 'foo.jpg' becomes 'foo_thumbnail.jpg'
276
+ def thumbnail_name_for(thumbnail = nil)
277
+ return filename if thumbnail.blank?
278
+ ext = nil
279
+ basename = filename.gsub /\.\w+$/ do |s|
280
+ ext = s; ''
281
+ end
282
+ # ImageScience doesn't create gif thumbnails, only pngs
283
+ ext.sub!(/gif$/, 'png') if attachment_options[:processor] == "ImageScience"
284
+ "#{basename}_#{thumbnail}#{ext}"
285
+ end
286
+
287
+ # Creates or updates the thumbnail for the current attachment.
288
+ def create_or_update_thumbnail(temp_file, file_name_suffix, *size)
289
+ thumbnailable? || raise(ThumbnailError.new("Can't create a thumbnail if the content type is not an image or there is no parent_id column"))
290
+ find_or_initialize_thumbnail(file_name_suffix).tap do |thumb|
291
+ thumb.temp_paths.unshift temp_file
292
+ thumb.send(:'attributes=', {
293
+ :content_type => content_type,
294
+ :filename => thumbnail_name_for(file_name_suffix),
295
+ :thumbnail_resize_options => size
296
+ }, false)
297
+ callback_with_args :before_thumbnail_saved, thumb
298
+ thumb.save!
299
+ end
300
+ end
301
+
302
+ # Sets the content type.
303
+ def content_type=(new_type)
304
+ write_attribute :content_type, new_type.to_s.strip
305
+ end
306
+
307
+ # Sanitizes a filename.
308
+ def filename=(new_name)
309
+ write_attribute :filename, sanitize_filename(new_name)
310
+ end
311
+
312
+ # Returns the width/height in a suitable format for the image_tag helper: (100x100)
313
+ def image_size
314
+ [width.to_s, height.to_s] * 'x'
315
+ end
316
+
317
+ # Returns true if the attachment data will be written to the storage system on the next save
318
+ def save_attachment?
319
+ File.file?(temp_path.to_s)
320
+ end
321
+
322
+ # nil placeholder in case this field is used in a form.
323
+ def uploaded_data() nil; end
324
+
325
+ # This method handles the uploaded file object. If you set the field name to uploaded_data, you don't need
326
+ # any special code in your controller.
327
+ #
328
+ # <% form_for :attachment, :html => { :multipart => true } do |f| -%>
329
+ # <p><%= f.file_field :uploaded_data %></p>
330
+ # <p><%= submit_tag :Save %>
331
+ # <% end -%>
332
+ #
333
+ # @attachment = Attachment.create! params[:attachment]
334
+ #
335
+ # TODO: Allow it to work with Merb tempfiles too.
336
+ def uploaded_data=(file_data)
337
+ if file_data.respond_to?(:content_type)
338
+ return nil if file_data.size == 0
339
+ self.content_type = file_data.content_type
340
+ self.filename = file_data.original_filename if respond_to?(:filename)
341
+ else
342
+ return nil if file_data.blank? || file_data['size'] == 0
343
+ self.content_type = file_data['content_type']
344
+ self.filename = file_data['filename']
345
+ file_data = file_data['tempfile']
346
+ end
347
+ if file_data.is_a?(StringIO)
348
+ file_data.rewind
349
+ set_temp_data file_data.read
350
+ else
351
+ self.temp_paths.unshift file_data
352
+ end
353
+ end
354
+
355
+ # Gets the latest temp path from the collection of temp paths. While working with an attachment,
356
+ # multiple Tempfile objects may be created for various processing purposes (resizing, for example).
357
+ # An array of all the tempfile objects is stored so that the Tempfile instance is held on to until
358
+ # it's not needed anymore. The collection is cleared after saving the attachment.
359
+ def temp_path
360
+ p = temp_paths.first
361
+ p.respond_to?(:path) ? p.path : p.to_s
362
+ end
363
+
364
+ # Gets an array of the currently used temp paths. Defaults to a copy of #full_filename.
365
+ def temp_paths
366
+ @temp_paths ||= (new_record? || !respond_to?(:full_filename) || !File.exist?(full_filename) ?
367
+ [] : [copy_to_temp_file(full_filename)])
368
+ end
369
+
370
+ # Gets the data from the latest temp file. This will read the file into memory.
371
+ def temp_data
372
+ save_attachment? ? File.read(temp_path) : nil
373
+ end
374
+
375
+ # Writes the given data to a Tempfile and adds it to the collection of temp files.
376
+ def set_temp_data(data)
377
+ temp_paths.unshift write_to_temp_file data unless data.nil?
378
+ end
379
+
380
+ # Copies the given file to a randomly named Tempfile.
381
+ def copy_to_temp_file(file)
382
+ self.class.copy_to_temp_file file, random_tempfile_filename
383
+ end
384
+
385
+ # Writes the given file to a randomly named Tempfile.
386
+ def write_to_temp_file(data)
387
+ self.class.write_to_temp_file data, random_tempfile_filename
388
+ end
389
+
390
+ # Stub for creating a temp file from the attachment data. This should be defined in the backend module.
391
+ def create_temp_file() end
392
+
393
+ # Allows you to work with a processed representation (RMagick, ImageScience, etc) of the attachment in a block.
394
+ #
395
+ # @attachment.with_image do |img|
396
+ # self.data = img.thumbnail(100, 100).to_blob
397
+ # end
398
+ #
399
+ def with_image(&block)
400
+ self.class.with_image(temp_path, &block)
401
+ end
402
+
403
+ protected
404
+ # Generates a unique filename for a Tempfile.
405
+ def random_tempfile_filename
406
+ "#{rand Time.now.to_i}#{filename || 'attachment'}"
407
+ end
408
+
409
+ def sanitize_filename(filename)
410
+ return unless filename
411
+ filename.strip.tap do |name|
412
+ # NOTE: File.basename doesn't work right with Windows paths on Unix
413
+ # get only the filename, not the whole path
414
+ name.gsub! /^.*(\\|\/)/, ''
415
+
416
+ # Finally, replace all non alphanumeric, underscore or periods with underscore
417
+ name.gsub! /[^A-Za-z0-9\.\-]/, '_'
418
+ end
419
+ end
420
+
421
+ # before_validation callback.
422
+ def set_size_from_temp_path
423
+ self.size = File.size(temp_path) if save_attachment?
424
+ end
425
+
426
+ # validates the size and content_type attributes according to the current model's options
427
+ def attachment_attributes_valid?
428
+ [:size, :content_type].each do |attr_name|
429
+ enum = attachment_options[attr_name]
430
+ if Object.const_defined?(:I18n) # Rails >= 2.2
431
+ errors.add attr_name, I18n.translate("activerecord.errors.messages.inclusion", attr_name => enum) unless enum.nil? || enum.include?(send(attr_name))
432
+ else
433
+ errors.add attr_name, ActiveRecord::Errors.default_error_messages[:inclusion] unless enum.nil? || enum.include?(send(attr_name))
434
+ end
435
+ end
436
+ end
437
+
438
+ # Initializes a new thumbnail with the given suffix.
439
+ def find_or_initialize_thumbnail(file_name_suffix)
440
+ respond_to?(:parent_id) ?
441
+ thumbnail_class.find_or_initialize_by_thumbnail_and_parent_id(file_name_suffix.to_s, id) :
442
+ thumbnail_class.find_or_initialize_by_thumbnail(file_name_suffix.to_s)
443
+ end
444
+
445
+ # Stub for a #process_attachment method in a processor
446
+ def process_attachment
447
+ @saved_attachment = save_attachment?
448
+ end
449
+
450
+ # Cleans up after processing. Thumbnails are created, the attachment is stored to the backend, and the temp_paths are cleared.
451
+ def after_process_attachment
452
+ if @saved_attachment
453
+ if respond_to?(:process_attachment_with_processing, true) && thumbnailable? && !attachment_options[:thumbnails].blank? && parent_id.nil?
454
+ temp_file = temp_path || create_temp_file
455
+ attachment_options[:thumbnails].each { |suffix, size| create_or_update_thumbnail(temp_file, suffix, *size) }
456
+ end
457
+ save_to_storage
458
+ @temp_paths.clear
459
+ @saved_attachment = nil
460
+ end
461
+ end
462
+
463
+ # Resizes the given processed img object with either the attachment resize options or the thumbnail resize options.
464
+ def resize_image_or_thumbnail!(img)
465
+ if (!respond_to?(:parent_id) || parent_id.nil?) && attachment_options[:resize_to] # parent image
466
+ resize_image(img, evaluate_parameter(attachment_options[:resize_to]))
467
+ elsif thumbnail_resize_options # thumbnail
468
+ resize_image(img, evaluate_parameter(thumbnail_resize_options))
469
+ end
470
+ end
471
+
472
+ # Determine what the parameter is and handle it
473
+ # Options are
474
+ # 1. String "100x50"
475
+ # 2. Array [100,50]
476
+ # 3. Method to return one of the above
477
+ def evaluate_parameter(param)
478
+ return param if param.is_a?(String)
479
+ return param if param.is_a?(Array) && param.length > 1
480
+ param = param[0] if param.is_a?(Array)
481
+ if param.is_a?(Symbol) && self.respond_to?(param)
482
+ self.send param
483
+ else
484
+ param
485
+ end
486
+ end
487
+
488
+
489
+ if defined?(Rails) && Rails::VERSION::MAJOR >= 3
490
+ def callback_with_args(method, arg = self)
491
+ send(method, arg) if respond_to?(method)
492
+ end
493
+ # Yanked from ActiveRecord::Callbacks, modified so I can pass args to the callbacks besides self.
494
+ # Only accept blocks, however
495
+ elsif ActiveSupport.const_defined?(:Callbacks)
496
+ # Rails 2.1 and beyond!
497
+ def callback_with_args(method, arg = self)
498
+ notify(method)
499
+
500
+ result = run_callbacks(method, { :object => arg }) { |result, object| result == false }
501
+
502
+ if result != false && respond_to_without_attributes?(method)
503
+ result = send(method)
504
+ end
505
+
506
+ result
507
+ end
508
+
509
+ def run_callbacks(kind, options = {}, &block)
510
+ options.reverse_merge!( :object => self )
511
+ self.class.send("#{kind}_callback_chain").run(options[:object], options, &block)
512
+ end
513
+ else
514
+ # Rails 2.0
515
+ def callback_with_args(method, arg = self)
516
+ notify(method)
517
+
518
+ result = nil
519
+ callbacks_for(method).each do |callback|
520
+ result = callback.call(self, arg)
521
+ return false if result == false
522
+ end
523
+ result
524
+ end
525
+ end
526
+
527
+ # Removes the thumbnails for the attachment, if it has any
528
+ def destroy_thumbnails
529
+ self.thumbnails.each { |thumbnail| thumbnail.destroy } if thumbnailable?
530
+ end
531
+ end
532
+ end
533
+ end