popel-attachment_fu 1.0.4

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