attachmerb_fu 0.0.1

Sign up to get free protection for your applications and to get access to all the features.
Files changed (36) hide show
  1. data/LICENSE +22 -0
  2. data/README +166 -0
  3. data/Rakefile +35 -0
  4. data/TODO +5 -0
  5. data/lib/amazon_s3.yml.tpl +14 -0
  6. data/lib/attachment_fu.rb +431 -0
  7. data/lib/attachmerb_fu.rb +446 -0
  8. data/lib/attachmerb_fu/backends/db_file_backend.rb +37 -0
  9. data/lib/attachmerb_fu/backends/file_system_backend.rb +95 -0
  10. data/lib/attachmerb_fu/backends/s3_backend.rb +307 -0
  11. data/lib/attachmerb_fu/merbtasks.rb +6 -0
  12. data/lib/attachmerb_fu/processors/image_science_processor.rb +60 -0
  13. data/lib/attachmerb_fu/processors/mini_magick_processor.rb +54 -0
  14. data/lib/attachmerb_fu/processors/rmagick_processor.rb +51 -0
  15. data/lib/geometry.rb +93 -0
  16. data/lib/tempfile_ext.rb +9 -0
  17. data/lib/test/amazon_s3.yml +6 -0
  18. data/lib/test/backends/db_file_test.rb +16 -0
  19. data/lib/test/backends/file_system_test.rb +80 -0
  20. data/lib/test/backends/remote/s3_test.rb +103 -0
  21. data/lib/test/base_attachment_tests.rb +57 -0
  22. data/lib/test/basic_test.rb +64 -0
  23. data/lib/test/database.yml +18 -0
  24. data/lib/test/extra_attachment_test.rb +57 -0
  25. data/lib/test/fixtures/attachment.rb +127 -0
  26. data/lib/test/fixtures/files/fake/rails.png +0 -0
  27. data/lib/test/fixtures/files/foo.txt +1 -0
  28. data/lib/test/fixtures/files/rails.png +0 -0
  29. data/lib/test/geometry_test.rb +101 -0
  30. data/lib/test/processors/image_science_test.rb +31 -0
  31. data/lib/test/processors/mini_magick_test.rb +31 -0
  32. data/lib/test/processors/rmagick_test.rb +241 -0
  33. data/lib/test/schema.rb +86 -0
  34. data/lib/test/test_helper.rb +142 -0
  35. data/lib/test/validation_test.rb +55 -0
  36. metadata +107 -0
data/LICENSE ADDED
@@ -0,0 +1,22 @@
1
+ Copyright (c) 2008 Michael Siebert
2
+
3
+ Original Rails Plugin (c) Rick Olson aka technoweenie
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining
6
+ a copy of this software and associated documentation files (the
7
+ "Software"), to deal in the Software without restriction, including
8
+ without limitation the rights to use, copy, modify, merge, publish,
9
+ distribute, sublicense, and/or sell copies of the Software, and to
10
+ permit persons to whom the Software is furnished to do so, subject to
11
+ the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be
14
+ included in all copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
20
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
21
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
22
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README ADDED
@@ -0,0 +1,166 @@
1
+ attachmerb-fu
2
+ =====================
3
+
4
+ attachmerb_fu is a port of Rick Olson's famous attachment_fu Rails plugin to merb. It tries to be as orm-agnostic as merb while having the same functionalities as the original plugin.
5
+
6
+ This plugin is still in a very alpha state and was only tested with datamapper orm, mini_magick image processor and filesystem storage. It may or may not work for your application
7
+
8
+ Note: attachmerb_fu requires Merb >= 0.5
9
+
10
+
11
+ attachmerb_fu functionality
12
+ ===========================
13
+
14
+ attachmerb_fu facilitates file uploads in Merb. 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.
15
+
16
+ There are three storage options for files uploaded through attachmerb_fu:
17
+ File system
18
+ Database file (currently not tested)
19
+ Amazon S3 (currently not tested)
20
+
21
+ 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.
22
+
23
+
24
+ attachmerb_fu models
25
+ ====================
26
+
27
+ 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).
28
+
29
+ In the model there are two methods made available by this plugins: has_attachment and validates_as_attachment.
30
+
31
+ has_attachment(options = {})
32
+ This method accepts the options in a hash:
33
+ :content_type # Allowed content types.
34
+ # Allows all by default. Use :image to allow all standard image types.
35
+ :min_size # Minimum size allowed.
36
+ # 1 byte is the default.
37
+ :max_size # Maximum size allowed.
38
+ # 1.megabyte is the default.
39
+ :size # Range of sizes allowed.
40
+ # (1..1.megabyte) is the default. This overrides the :min_size and :max_size options.
41
+ :resize_to # Used by RMagick to resize images.
42
+ # Pass either an array of width/height, or a geometry string.
43
+ :thumbnails # Specifies a set of thumbnails to generate.
44
+ # This accepts a hash of filename suffixes and RMagick resizing options.
45
+ # This option need only be included if you want thumbnailing.
46
+ :thumbnail_class # Set which model class to use for thumbnails.
47
+ # This current attachment class is used by default.
48
+ :path_prefix # path to store the uploaded files.
49
+ # Uses public/#{table_name} by default for the filesystem, and just #{table_name} for the S3 backend.
50
+ # Setting this sets the :storage to :file_system.
51
+ :storage # Specifies the storage system to use..
52
+ # Defaults to :db_file. Options are :file_system, :db_file, and :s3.
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
+
56
+
57
+ Examples:
58
+ has_attachment :max_size => 1.kilobyte
59
+ has_attachment :size => 1.megabyte..2.megabytes
60
+ has_attachment :content_type => 'application/pdf'
61
+ has_attachment :content_type => ['application/pdf', 'application/msword', 'text/plain']
62
+ has_attachment :content_type => :image, :resize_to => [50,50]
63
+ has_attachment :content_type => ['application/pdf', :image], :resize_to => 'x50'
64
+ has_attachment :thumbnails => { :thumb => [50, 50], :geometry => 'x50' }
65
+ has_attachment :storage => :file_system, :path_prefix => 'public/files'
66
+ has_attachment :storage => :file_system, :path_prefix => 'public/files',
67
+ :content_type => :image, :resize_to => [50,50]
68
+ has_attachment :storage => :file_system, :path_prefix => 'public/files',
69
+ :thumbnails => { :thumb => [50, 50], :geometry => 'x50' }
70
+ has_attachment :storage => :s3
71
+
72
+ validates_as_attachment
73
+ 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.
74
+
75
+ Example:
76
+ validates_as_attachment
77
+
78
+
79
+ attachmerb_fu migrations
80
+ ========================
81
+
82
+ Fields for attachmerb_fu metadata tables...
83
+ in general:
84
+ size, :integer # file size in bytes
85
+ content_type, :string # mime type, ex: application/mp3
86
+ filename, :string # sanitized filename
87
+ that reference images:
88
+ height, :integer # in pixels
89
+ width, :integer # in pixels
90
+ that reference images that will be thumbnailed:
91
+ parent_id, :integer # id of parent image (on the same table, a self-referencing foreign-key).
92
+ # Only populated if the current object is a thumbnail.
93
+ thumbnail, :string # the 'type' of thumbnail this attachment record describes.
94
+ # Only populated if the current object is a thumbnail.
95
+ # Usage:
96
+ # [ In Model 'Avatar' ]
97
+ # has_attachment :content_type => :image,
98
+ # :storage => :file_system,
99
+ # :max_size => 500.kilobytes,
100
+ # :resize_to => '320x200>',
101
+ # :thumbnails => { :small => '10x10>',
102
+ # :thumb => '100x100>' }
103
+ # [ Elsewhere ]
104
+ # @user.avatar.thumbnails.first.thumbnail #=> 'small'
105
+ that reference files stored in the database (:db_file):
106
+ db_file_id, :integer # id of the file in the database (foreign key)
107
+
108
+ Field for attachmerb_fu db_files table:
109
+ data, :binary # binary file data, for use in database file storage
110
+
111
+
112
+ attachmerb_fu views
113
+ ===================
114
+
115
+ There are two main views tasks that will be directly affected by attachmerb_fu: upload forms and displaying uploaded images.
116
+
117
+ There are two parts of the upload form that differ from typical usage.
118
+ 1. Include ':multipart => true' in the html options of the form_for tag.
119
+ Example:
120
+ <% form_for(:attachment_metadata, :url => { :action => "create" }, :html => { :multipart => true }) do |form| %>
121
+
122
+ 2. Use the file_field helper with :uploaded_data as the field name.
123
+ Example:
124
+ <%= form.file_field :uploaded_data %>
125
+
126
+ Displaying uploaded images is made easy by the public_filename method of the ActiveRecord attachment objects using file system and s3 storage.
127
+
128
+ public_filename(thumbnail = nil)
129
+ Returns the public path to the file. If a thumbnail prefix is specified it will return the public file path to the corresponding thumbnail.
130
+ Examples:
131
+ attachment_obj.public_filename #=> /attachments/2/file.jpg
132
+ attachment_obj.public_filename(:thumb) #=> /attachments/2/file_thumb.jpg
133
+ attachment_obj.public_filename(:small) #=> /attachments/2/file_small.jpg
134
+
135
+ When serving files from database storage, doing more than simply downloading the file is beyond the scope of this document.
136
+
137
+
138
+ attachmerb_fu controllers
139
+ =========================
140
+
141
+ There are two considerations to take into account when using attachmerb_fu in controllers.
142
+
143
+ The first is when the files have no publicly accessible path and need to be downloaded through an action.
144
+
145
+ Example:
146
+ def readme
147
+ send_file '/path/to/readme.txt', :type => 'plain/text', :disposition => 'inline'
148
+ end
149
+
150
+ See the possible values for send_file for reference.
151
+
152
+
153
+ The second is when saving the file when submitted from a form.
154
+ Example in view:
155
+ <%= form.file_field :attachable, :uploaded_data %>
156
+
157
+ Example in controller:
158
+ def create
159
+ @attachable_file = AttachmentMetadataModel.new(params[:attachable])
160
+ if @attachable_file.save
161
+ flash[:notice] = 'Attachment was successfully created.'
162
+ redirect_to attachable_url(@attachable_file)
163
+ else
164
+ render :action => :new
165
+ end
166
+ end
@@ -0,0 +1,35 @@
1
+ require 'rubygems'
2
+ require 'rake/gempackagetask'
3
+
4
+ PLUGIN = "attachmerb_fu"
5
+ NAME = "attachmerb_fu"
6
+ VERSION = "0.0.1"
7
+ AUTHOR = "Michael Siebert"
8
+ EMAIL = "siebertm85@googlemail.com"
9
+ HOMEPAGE = "http://merb-plugins.rubyforge.org/attachmerb_fu/"
10
+ SUMMARY = "Merb plugin that provides a port of attachment_fu to merb"
11
+
12
+ spec = Gem::Specification.new do |s|
13
+ s.name = NAME
14
+ s.version = VERSION
15
+ s.platform = Gem::Platform::RUBY
16
+ s.has_rdoc = true
17
+ s.extra_rdoc_files = ["README", "LICENSE", 'TODO']
18
+ s.summary = SUMMARY
19
+ s.description = s.summary
20
+ s.author = AUTHOR
21
+ s.email = EMAIL
22
+ s.homepage = HOMEPAGE
23
+ s.add_dependency('merb', '>= 0.5.0')
24
+ s.require_path = 'lib'
25
+ s.autorequire = PLUGIN
26
+ s.files = %w(LICENSE README Rakefile TODO) + Dir.glob("{lib,specs}/**/*")
27
+ end
28
+
29
+ Rake::GemPackageTask.new(spec) do |pkg|
30
+ pkg.gem_spec = spec
31
+ end
32
+
33
+ task :install => [:package] do
34
+ sh %{sudo gem install pkg/#{NAME}-#{VERSION}}
35
+ end
data/TODO ADDED
@@ -0,0 +1,5 @@
1
+ TODO:
2
+ Fix LICENSE with your name
3
+ Fix Rakefile with your name and contact info
4
+ Add your code to lib/attachmerb_fu.rb
5
+ Add your Merb rake tasks to lib/attachmerb_fu/merbtasks.rb
@@ -0,0 +1,14 @@
1
+ development:
2
+ bucket_name: appname_development
3
+ access_key_id:
4
+ secret_access_key:
5
+
6
+ test:
7
+ bucket_name: appname_test
8
+ access_key_id:
9
+ secret_access_key:
10
+
11
+ production:
12
+ bucket_name: appname
13
+ access_key_id:
14
+ secret_access_key:
@@ -0,0 +1,431 @@
1
+ module Technoweenie # :nodoc:
2
+ module AttachmentFu # :nodoc:
3
+ @@default_processors = %w(ImageScience Rmagick MiniMagick)
4
+ @@tempfile_path = File.join(Merb.root, 'tmp', 'attachment_fu')
5
+ @@content_types = ['image/jpeg', 'image/pjpeg', 'image/gif', 'image/png', 'image/x-png', 'image/jpg']
6
+ attr_reader :content_types, :tempfile_path, :default_processors
7
+ attr_writer :tempfile_path
8
+
9
+ [:content_types, :tempfile_path, :default_processors].each do |m|
10
+ class_eval "def self.#{m}() @@#{m} end"
11
+ end
12
+
13
+ class ThumbnailError < StandardError; end
14
+ class AttachmentError < StandardError; end
15
+
16
+ module ActMethods
17
+ # Options:
18
+ # * <tt>:content_type</tt> - Allowed content types. Allows all by default. Use :image to allow all standard image types.
19
+ # * <tt>:min_size</tt> - Minimum size allowed. 1 byte is the default.
20
+ # * <tt>:max_size</tt> - Maximum size allowed. 1.megabyte is the default.
21
+ # * <tt>:size</tt> - Range of sizes allowed. (1..1.megabyte) is the default. This overrides the :min_size and :max_size options.
22
+ # * <tt>:resize_to</tt> - Used by RMagick to resize images. Pass either an array of width/height, or a geometry string.
23
+ # * <tt>:thumbnails</tt> - Specifies a set of thumbnails to generate. This accepts a hash of filename suffixes and RMagick resizing options.
24
+ # * <tt>:thumbnail_class</tt> - Set what class to use for thumbnails. This attachment class is used by default.
25
+ # * <tt>:path_prefix</tt> - path to store the uploaded files. Uses public/#{table_name} by default for the filesystem, and just #{table_name}
26
+ # for the S3 backend. Setting this sets the :storage to :file_system.
27
+ # * <tt>:storage</tt> - Use :file_system to specify the attachment data is stored with the file system. Defaults to :db_system.
28
+ #
29
+ # Examples:
30
+ # has_attachment :max_size => 1.kilobyte
31
+ # has_attachment :size => 1.megabyte..2.megabytes
32
+ # has_attachment :content_type => 'application/pdf'
33
+ # has_attachment :content_type => ['application/pdf', 'application/msword', 'text/plain']
34
+ # has_attachment :content_type => :image, :resize_to => [50,50]
35
+ # has_attachment :content_type => ['application/pdf', :image], :resize_to => 'x50'
36
+ # has_attachment :thumbnails => { :thumb => [50, 50], :geometry => 'x50' }
37
+ # has_attachment :storage => :file_system, :path_prefix => 'public/files'
38
+ # has_attachment :storage => :file_system, :path_prefix => 'public/files',
39
+ # :content_type => :image, :resize_to => [50,50]
40
+ # has_attachment :storage => :file_system, :path_prefix => 'public/files',
41
+ # :thumbnails => { :thumb => [50, 50], :geometry => 'x50' }
42
+ # has_attachment :storage => :s3
43
+ def has_attachment(options = {})
44
+ # this allows you to redefine the acts' options for each subclass, however
45
+ options[:min_size] ||= 1
46
+ options[:max_size] ||= 1024*1024*1024
47
+ options[:size] ||= (options[:min_size]..options[:max_size])
48
+ options[:thumbnails] ||= {}
49
+ options[:thumbnail_class] ||= self
50
+ options[:s3_access] ||= :public_read
51
+ options[:content_type] = [options[:content_type]].flatten.collect! { |t| t == :image ? Technoweenie::AttachmentFu.content_types : t }.flatten unless options[:content_type].nil?
52
+
53
+ unless options[:thumbnails].is_a?(Hash)
54
+ raise ArgumentError, ":thumbnails option should be a hash: e.g. :thumbnails => { :foo => '50x50' }"
55
+ end
56
+
57
+ # doing these shenanigans so that #attachment_options is available to processors and backends
58
+ class_inheritable_accessor :attachment_options
59
+ self.attachment_options = options
60
+
61
+ # only need to define these once on a class
62
+ unless included_modules.include?(InstanceMethods)
63
+ attr_accessor :thumbnail_resize_options
64
+
65
+ attachment_options[:storage] ||= :file_system
66
+ attachment_options[:path_prefix] ||= attachment_options[:file_system_path]
67
+ if attachment_options[:path_prefix].nil?
68
+ attachment_options[:path_prefix] = File.join("public", table.name)
69
+ end
70
+ attachment_options[:path_prefix] = attachment_options[:path_prefix][1..-1] if options[:path_prefix][0] == '/'
71
+
72
+ has_many :thumbnails, :class_name => attachment_options[:thumbnail_class].to_s, :foreign_key => 'parent_id'
73
+ belongs_to :parent, :class_name => table.klass.to_s, :foreign_key => 'parent_id'
74
+
75
+ before_update :rename_file
76
+ before_destroy :destroy_thumbnails
77
+
78
+ before_validation :set_size_from_temp_path
79
+ after_save :after_process_attachment
80
+ after_destroy :destroy_file
81
+ extend ClassMethods
82
+ include InstanceMethods
83
+
84
+ backend = "#{options[:storage].to_s.classify}Backend"
85
+ require "backends/#{backend.snake_case}"
86
+ include Technoweenie::AttachmentFu::Backends.const_get(backend)
87
+
88
+ case attachment_options[:processor]
89
+ when :none
90
+ when nil
91
+ processors = Technoweenie::AttachmentFu.default_processors.dup
92
+ begin
93
+ if processors.any?
94
+ attachment_options[:processor] = "#{processors.first}Processor"
95
+ require "processors/#{attachment_options[:processor].snake_case}"
96
+
97
+ include Technoweenie::AttachmentFu::Processors.const_get(attachment_options[:processor])
98
+ end
99
+ rescue LoadError
100
+ processors.shift
101
+ retry
102
+ end
103
+ else
104
+ begin
105
+ processor = "#{options[:processor].to_s.classify}Processor"
106
+ require "processors/#{processor.snake_case}"
107
+ include Technoweenie::AttachmentFu::Processors.const_get(processor)
108
+ rescue LoadError
109
+ puts "Problems loading #{processor}: #{$!}"
110
+ end
111
+ end
112
+
113
+ after_validation :process_attachment
114
+ end
115
+ end
116
+ end
117
+
118
+ module ClassMethods
119
+ def content_types
120
+ Technoweenie::AttachmentFu.content_types
121
+ end
122
+
123
+ # Performs common validations for attachment models.
124
+ def validates_as_attachment
125
+ validates_presence_of :size, :content_type, :filename
126
+ validate :attachment_attributes_valid?
127
+ end
128
+
129
+ # Returns true or false if the given content type is recognized as an image.
130
+ def image?(content_type)
131
+ content_types.include?(content_type)
132
+ end
133
+
134
+ # Callback after an image has been resized.
135
+ #
136
+ # class Foo < ActiveRecord::Base
137
+ # acts_as_attachment
138
+ # after_resize do |record, img|
139
+ # record.aspect_ratio = img.columns.to_f / img.rows.to_f
140
+ # end
141
+ # end
142
+ def after_resize(&block)
143
+ write_inheritable_array(:after_resize, [block])
144
+ end
145
+
146
+ # Callback after an attachment has been saved either to the file system or the DB.
147
+ # Only called if the file has been changed, not necessarily if the record is updated.
148
+ #
149
+ # class Foo < ActiveRecord::Base
150
+ # acts_as_attachment
151
+ # after_attachment_saved do |record|
152
+ # ...
153
+ # end
154
+ # end
155
+ def after_attachment_saved(&block)
156
+ write_inheritable_array(:after_attachment_saved, [block])
157
+ end
158
+
159
+ # Callback before a thumbnail is saved. Use this to pass any necessary extra attributes that may be required.
160
+ #
161
+ # class Foo < ActiveRecord::Base
162
+ # acts_as_attachment
163
+ # before_thumbnail_saved do |record, thumbnail|
164
+ # ...
165
+ # end
166
+ # end
167
+ def before_thumbnail_saved(&block)
168
+ write_inheritable_array(:before_thumbnail_saved, [block])
169
+ end
170
+
171
+ # Get the thumbnail class, which is the current attachment class by default.
172
+ # Configure this with the :thumbnail_class option.
173
+ def thumbnail_class
174
+ attachment_options[:thumbnail_class] = attachment_options[:thumbnail_class].constantize unless attachment_options[:thumbnail_class].is_a?(Class)
175
+ attachment_options[:thumbnail_class]
176
+ end
177
+
178
+ # Copies the given file path to a new tempfile, returning the closed tempfile.
179
+ def copy_to_temp_file(file, temp_base_name)
180
+ returning Tempfile.new(temp_base_name, Technoweenie::AttachmentFu.tempfile_path) do |tmp|
181
+ tmp.close
182
+ FileUtils.cp file, tmp.path
183
+ end
184
+ end
185
+
186
+ # Writes the given data to a new tempfile, returning the closed tempfile.
187
+ def write_to_temp_file(data, temp_base_name)
188
+ returning Tempfile.new(temp_base_name, Technoweenie::AttachmentFu.tempfile_path) do |tmp|
189
+ tmp.binmode
190
+ tmp.write data
191
+ tmp.close
192
+ end
193
+ end
194
+ end
195
+
196
+ module InstanceMethods
197
+ # Checks whether the attachment's content type is an image content type
198
+ def image?
199
+ self.class.image?(content_type)
200
+ end
201
+
202
+ # Returns true/false if an attachment is thumbnailable. A thumbnailable attachment has an image content type and the parent_id attribute.
203
+ def thumbnailable?
204
+ image? && respond_to?(:parent_id) && parent_id.nil?
205
+ end
206
+
207
+ # Returns the class used to create new thumbnails for this attachment.
208
+ def thumbnail_class
209
+ self.class.thumbnail_class
210
+ end
211
+
212
+ # Gets the thumbnail name for a filename. 'foo.jpg' becomes 'foo_thumbnail.jpg'
213
+ def thumbnail_name_for(thumbnail = nil)
214
+ return filename if thumbnail.blank?
215
+ ext = nil
216
+ basename = filename.gsub /\.\w+$/ do |s|
217
+ ext = s; ''
218
+ end
219
+ # ImageScience doesn't create gif thumbnails, only pngs
220
+ ext.sub!(/gif$/, 'png') if attachment_options[:processor] == "ImageScienceProcessor"
221
+ "#{basename}_#{thumbnail}#{ext}"
222
+ end
223
+
224
+ # Creates or updates the thumbnail for the current attachment.
225
+ def create_or_update_thumbnail(temp_file, file_name_suffix, *size)
226
+ thumbnailable? || raise(ThumbnailError.new("Can't create a thumbnail if the content type is not an image or there is no parent_id column"))
227
+ returning find_or_initialize_thumbnail(file_name_suffix) do |thumb|
228
+ thumb.attributes = {
229
+ :content_type => content_type,
230
+ :filename => thumbnail_name_for(file_name_suffix),
231
+ :temp_path => temp_file,
232
+ :thumbnail_resize_options => size
233
+ }
234
+ callback_with_args :before_thumbnail_saved, thumb
235
+ thumb.save!
236
+ end
237
+ end
238
+
239
+ # Sets the content type.
240
+ def content_type=(new_type)
241
+ write_attribute :content_type, new_type.to_s.strip
242
+ end
243
+
244
+ # Sanitizes a filename.
245
+ def filename=(new_name)
246
+ write_attribute :filename, sanitize_filename(new_name)
247
+ end
248
+
249
+ # Returns the width/height in a suitable format for the image_tag helper: (100x100)
250
+ def image_size
251
+ [width.to_s, height.to_s] * 'x'
252
+ end
253
+
254
+ # Returns true if the attachment data will be written to the storage system on the next save
255
+ def save_attachment?
256
+ File.file?(temp_path.to_s)
257
+ end
258
+
259
+ # nil placeholder in case this field is used in a form.
260
+ def uploaded_data() nil; end
261
+
262
+ # This method handles the uploaded file object. If you set the field name to uploaded_data, you don't need
263
+ # any special code in your controller.
264
+ #
265
+ # <% form_for :attachment, :html => { :multipart => true } do |f| -%>
266
+ # <p><%= f.file_field :uploaded_data %></p>
267
+ # <p><%= submit_tag :Save %>
268
+ # <% end -%>
269
+ #
270
+ # @attachment = Attachment.create! params[:attachment]
271
+ #
272
+ # TODO: Allow it to work with Merb tempfiles too.
273
+ def uploaded_data=(file_data)
274
+
275
+ return nil if file_data.nil? || file_data["size"] == 0
276
+ self.content_type = file_data["content_type"]
277
+ self.filename = file_data["filename"] if respond_to?(:filename)
278
+ data = file_data["tempfile"]
279
+ if data.is_a?(StringIO)
280
+ data.rewind
281
+ self.temp_data = data.read
282
+ else
283
+ self.temp_path = data.path
284
+ end
285
+ end
286
+
287
+ # Gets the latest temp path from the collection of temp paths. While working with an attachment,
288
+ # multiple Tempfile objects may be created for various processing purposes (resizing, for example).
289
+ # An array of all the tempfile objects is stored so that the Tempfile instance is held on to until
290
+ # it's not needed anymore. The collection is cleared after saving the attachment.
291
+ def temp_path
292
+ p = temp_paths.first
293
+ p.respond_to?(:path) ? p.path : p.to_s
294
+ end
295
+
296
+ # Gets an array of the currently used temp paths. Defaults to a copy of #full_filename.
297
+ def temp_paths
298
+ @temp_paths ||= (new_record? || !File.exist?(full_filename)) ? [] : [copy_to_temp_file(full_filename)]
299
+ end
300
+
301
+ # Adds a new temp_path to the array. This should take a string or a Tempfile. This class makes no
302
+ # attempt to remove the files, so Tempfiles should be used. Tempfiles remove themselves when they go out of scope.
303
+ # You can also use string paths for temporary files, such as those used for uploaded files in a web server.
304
+ def temp_path=(value)
305
+ temp_paths.unshift value
306
+ temp_path
307
+ end
308
+
309
+ # Gets the data from the latest temp file. This will read the file into memory.
310
+ def temp_data
311
+ save_attachment? ? File.read(temp_path) : nil
312
+ end
313
+
314
+ # Writes the given data to a Tempfile and adds it to the collection of temp files.
315
+ def temp_data=(data)
316
+ self.temp_path = write_to_temp_file data unless data.nil?
317
+ end
318
+
319
+ # Copies the given file to a randomly named Tempfile.
320
+ def copy_to_temp_file(file)
321
+ self.class.copy_to_temp_file file, random_tempfile_filename
322
+ end
323
+
324
+ # Writes the given file to a randomly named Tempfile.
325
+ def write_to_temp_file(data)
326
+ self.class.write_to_temp_file data, random_tempfile_filename
327
+ end
328
+
329
+ # Stub for creating a temp file from the attachment data. This should be defined in the backend module.
330
+ def create_temp_file() end
331
+
332
+ # Allows you to work with a processed representation (RMagick, ImageScience, etc) of the attachment in a block.
333
+ #
334
+ # @attachment.with_image do |img|
335
+ # self.data = img.thumbnail(100, 100).to_blob
336
+ # end
337
+ #
338
+ def with_image(&block)
339
+ self.class.with_image(temp_path, &block)
340
+ end
341
+
342
+ protected
343
+ # Generates a unique filename for a Tempfile.
344
+ def random_tempfile_filename
345
+ "#{rand Time.now.to_i}#{filename || 'attachment'}"
346
+ end
347
+
348
+ def sanitize_filename(filename)
349
+ returning filename.strip do |name|
350
+ # NOTE: File.basename doesn't work right with Windows paths on Unix
351
+ # get only the filename, not the whole path
352
+ name.gsub! /^.*(\\|\/)/, ''
353
+
354
+ # Finally, replace all non alphanumeric, underscore or periods with underscore
355
+ name.gsub! /[^\w\.\-]/, '_'
356
+ end
357
+ end
358
+
359
+ # before_validation callback.
360
+ def set_size_from_temp_path
361
+ self.size = File.size(temp_path) if save_attachment?
362
+ end
363
+
364
+ # validates the size and content_type attributes according to the current model's options
365
+ def attachment_attributes_valid?
366
+ [:size, :content_type].each do |attr_name|
367
+ enum = attachment_options[attr_name]
368
+ errors.add attr_name, ActiveRecord::Errors.default_error_messages[:inclusion] unless enum.nil? || enum.include?(send(attr_name))
369
+ end
370
+ end
371
+
372
+ # Initializes a new thumbnail with the given suffix.
373
+ def find_or_initialize_thumbnail(file_name_suffix)
374
+ if respond_to?(:parent_id)
375
+ args = { :thumbnail => file_name_suffix.to_s, :parent_id => id}
376
+ else
377
+ args = { :thumbnail => file_name_suffix.to_s}
378
+ end
379
+
380
+ thumbnail_class.first(args) || thumbnail_class.new(args)
381
+ end
382
+
383
+ # Stub for a #process_attachment method in a processor
384
+ def process_attachment
385
+ @saved_attachment = save_attachment?
386
+ end
387
+
388
+ # Cleans up after processing. Thumbnails are created, the attachment is stored to the backend, and the temp_paths are cleared.
389
+ def after_process_attachment
390
+ if @saved_attachment
391
+ if respond_to?(:process_attachment_with_processing) && thumbnailable? && !attachment_options[:thumbnails].blank? && parent_id.nil?
392
+ temp_file = temp_path || create_temp_file
393
+ attachment_options[:thumbnails].each { |suffix, size| create_or_update_thumbnail(temp_file, suffix, *size) }
394
+ end
395
+ save_to_storage
396
+ @temp_paths.clear
397
+ @saved_attachment = nil
398
+ # callback :after_attachment_saved
399
+ end
400
+ end
401
+
402
+ # Resizes the given processed img object with either the attachment resize options or the thumbnail resize options.
403
+ def resize_image_or_thumbnail!(img)
404
+ if (!respond_to?(:parent_id) || parent_id.nil?) && attachment_options[:resize_to] # parent image
405
+ resize_image(img, attachment_options[:resize_to])
406
+ elsif thumbnail_resize_options # thumbnail
407
+ resize_image(img, thumbnail_resize_options)
408
+ end
409
+ end
410
+
411
+ # Yanked from ActiveRecord::Callbacks, modified so I can pass args to the callbacks besides self.
412
+ # Only accept blocks, however
413
+ def callback_with_args(method, arg = self)
414
+ # notify(method)
415
+ #
416
+ # result = nil
417
+ # callbacks_for(method).each do |callback|
418
+ # result = callback.call(self, arg)
419
+ # return false if result == false
420
+ # end
421
+ #
422
+ # return result
423
+ end
424
+
425
+ # Removes the thumbnails for the attachment, if it has any
426
+ def destroy_thumbnails
427
+ self.thumbnails.each { |thumbnail| thumbnail.destroy } if thumbnailable?
428
+ end
429
+ end
430
+ end
431
+ end