├── test ├── fixtures │ ├── files │ │ ├── foo.txt │ │ ├── rails.png │ │ └── fake │ │ │ └── rails.png │ └── attachment.rb ├── database.yml ├── backends │ ├── db_file_test.rb │ ├── remote │ │ └── s3_test.rb │ └── file_system_test.rb ├── processors │ ├── gd2_test.rb │ ├── image_science_test.rb │ ├── core_image_test.rb │ ├── mini_magick_test.rb │ └── rmagick_test.rb ├── validation_test.rb ├── extra_attachment_test.rb ├── base_attachment_tests.rb ├── basic_test.rb ├── geometry_test.rb ├── schema.rb └── test_helper.rb ├── .gitignore ├── install.rb ├── amazon_s3.yml.tpl ├── Rakefile ├── init.rb ├── vendor └── red_artisan │ └── core_image │ ├── filters │ ├── quality.rb │ ├── color.rb │ ├── perspective.rb │ ├── effects.rb │ ├── watermark.rb │ └── scale.rb │ └── processor.rb ├── lib ├── technoweenie │ ├── attachment_fu │ │ ├── backends │ │ │ ├── db_file_backend.rb │ │ │ ├── file_system_backend.rb │ │ │ └── s3_backend.rb │ │ └── processors │ │ │ ├── gd2_processor.rb │ │ │ ├── core_image_processor.rb │ │ │ ├── image_science_processor.rb │ │ │ ├── rmagick_processor.rb │ │ │ └── mini_magick_processor.rb │ └── attachment_fu.rb └── geometry.rb ├── CHANGELOG └── README /test/fixtures/files/foo.txt: -------------------------------------------------------------------------------- 1 | foo -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | test/amazon_s3.yml 2 | test/debug.log 3 | -------------------------------------------------------------------------------- /test/fixtures/files/rails.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Unity-Technologies/attachment_fu/master/test/fixtures/files/rails.png -------------------------------------------------------------------------------- /test/fixtures/files/fake/rails.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Unity-Technologies/attachment_fu/master/test/fixtures/files/fake/rails.png -------------------------------------------------------------------------------- /install.rb: -------------------------------------------------------------------------------- 1 | require 'fileutils' 2 | 3 | s3_config = File.dirname(__FILE__) + '/../../../config/amazon_s3.yml' 4 | FileUtils.cp File.dirname(__FILE__) + '/amazon_s3.yml.tpl', s3_config unless File.exist?(s3_config) 5 | puts IO.read(File.join(File.dirname(__FILE__), 'README')) -------------------------------------------------------------------------------- /amazon_s3.yml.tpl: -------------------------------------------------------------------------------- 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: 15 | -------------------------------------------------------------------------------- /test/database.yml: -------------------------------------------------------------------------------- 1 | sqlite: 2 | :adapter: sqlite 3 | :dbfile: attachment_fu_plugin.sqlite.db 4 | sqlite3: 5 | :adapter: sqlite3 6 | :dbfile: attachment_fu_plugin.sqlite3.db 7 | postgresql: 8 | :adapter: postgresql 9 | :username: postgres 10 | :password: postgres 11 | :database: attachment_fu_plugin_test 12 | :min_messages: ERROR 13 | mysql: 14 | :adapter: mysql 15 | :host: localhost 16 | :username: rails 17 | :password: 18 | :database: attachment_fu_plugin_test -------------------------------------------------------------------------------- /test/backends/db_file_test.rb: -------------------------------------------------------------------------------- 1 | require File.expand_path(File.join(File.dirname(__FILE__), '..', 'test_helper')) 2 | 3 | class DbFileTest < Test::Unit::TestCase 4 | include BaseAttachmentTests 5 | attachment_model Attachment 6 | 7 | def test_should_call_after_attachment_saved(klass = Attachment) 8 | attachment_model.saves = 0 9 | assert_created do 10 | upload_file :filename => '/files/rails.png' 11 | end 12 | assert_equal 1, attachment_model.saves 13 | end 14 | 15 | test_against_subclass :test_should_call_after_attachment_saved, Attachment 16 | end -------------------------------------------------------------------------------- /Rakefile: -------------------------------------------------------------------------------- 1 | require 'rake' 2 | require 'rake/testtask' 3 | require 'rake/rdoctask' 4 | 5 | desc 'Default: run unit tests.' 6 | task :default => :test 7 | 8 | desc 'Test the attachment_fu plugin.' 9 | Rake::TestTask.new(:test) do |t| 10 | t.libs << 'lib' 11 | t.pattern = 'test/**/*_test.rb' 12 | t.verbose = true 13 | end 14 | 15 | desc 'Generate documentation for the attachment_fu plugin.' 16 | Rake::RDocTask.new(:rdoc) do |rdoc| 17 | rdoc.rdoc_dir = 'rdoc' 18 | rdoc.title = 'ActsAsAttachment' 19 | rdoc.options << '--line-numbers --inline-source' 20 | rdoc.rdoc_files.include('README') 21 | rdoc.rdoc_files.include('lib/**/*.rb') 22 | end 23 | -------------------------------------------------------------------------------- /init.rb: -------------------------------------------------------------------------------- 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, ext) 8 | end 9 | end 10 | 11 | require 'geometry' 12 | ActiveRecord::Base.send(:extend, Technoweenie::AttachmentFu::ActMethods) 13 | Technoweenie::AttachmentFu.tempfile_path = ATTACHMENT_FU_TEMPFILE_PATH if Object.const_defined?(:ATTACHMENT_FU_TEMPFILE_PATH) 14 | FileUtils.mkdir_p Technoweenie::AttachmentFu.tempfile_path 15 | 16 | $:.unshift(File.dirname(__FILE__) + '/vendor') 17 | -------------------------------------------------------------------------------- /vendor/red_artisan/core_image/filters/quality.rb: -------------------------------------------------------------------------------- 1 | module RedArtisan 2 | module CoreImage 3 | module Filters 4 | module Quality 5 | 6 | def reduce_noise(level = 0.02, sharpness = 0.4) 7 | create_core_image_context(@original.extent.size.width, @original.extent.size.height) 8 | 9 | @original.noise_reduction :inputNoiseLevel => level, :inputSharpness => sharpness do |noise_reduced| 10 | @target = noise_reduced 11 | end 12 | end 13 | 14 | def adjust_exposure(input_ev = 0.5) 15 | create_core_image_context(@original.extent.size.width, @original.extent.size.height) 16 | 17 | @original.exposure_adjust :inputEV => input_ev do |adjusted| 18 | @target = adjusted 19 | end 20 | end 21 | 22 | end 23 | end 24 | end 25 | end -------------------------------------------------------------------------------- /vendor/red_artisan/core_image/filters/color.rb: -------------------------------------------------------------------------------- 1 | module RedArtisan 2 | module CoreImage 3 | module Filters 4 | module Color 5 | 6 | def greyscale(color = nil, intensity = 1.00) 7 | create_core_image_context(@original.extent.size.width, @original.extent.size.height) 8 | 9 | color = OSX::CIColor.colorWithString("1.0 1.0 1.0 1.0") unless color 10 | 11 | @original.color_monochrome :inputColor => color, :inputIntensity => intensity do |greyscale| 12 | @target = greyscale 13 | end 14 | end 15 | 16 | def sepia(intensity = 1.00) 17 | create_core_image_context(@original.extent.size.width, @original.extent.size.height) 18 | 19 | @original.sepia_tone :inputIntensity => intensity do |sepia| 20 | @target = sepia 21 | end 22 | end 23 | 24 | end 25 | end 26 | end 27 | end -------------------------------------------------------------------------------- /test/processors/gd2_test.rb: -------------------------------------------------------------------------------- 1 | require File.expand_path(File.join(File.dirname(__FILE__), '..', 'test_helper')) 2 | 3 | class GD2Test < Test::Unit::TestCase 4 | attachment_model GD2Attachment 5 | 6 | if Object.const_defined?(:GD2) 7 | def test_should_resize_image 8 | attachment = upload_file :filename => '/files/rails.png' 9 | assert_valid attachment 10 | assert attachment.image? 11 | # test gd2 thumbnail 12 | assert_equal 43, attachment.width 13 | assert_equal 55, attachment.height 14 | 15 | thumb = attachment.thumbnails.detect { |t| t.filename =~ /_thumb/ } 16 | geo = attachment.thumbnails.detect { |t| t.filename =~ /_geometry/ } 17 | 18 | # test exact resize dimensions 19 | assert_equal 50, thumb.width 20 | assert_equal 51, thumb.height 21 | 22 | # test geometry string 23 | assert_equal 31, geo.width 24 | assert_equal 40, geo.height 25 | end 26 | else 27 | def test_flunk 28 | puts "GD2 not loaded, tests not running" 29 | end 30 | end 31 | end -------------------------------------------------------------------------------- /vendor/red_artisan/core_image/filters/perspective.rb: -------------------------------------------------------------------------------- 1 | module RedArtisan 2 | module CoreImage 3 | module Filters 4 | module Perspective 5 | 6 | def perspective(top_left, top_right, bottom_left, bottom_right) 7 | create_core_image_context(@original.extent.size.width, @original.extent.size.height) 8 | 9 | @original.perspective_transform :inputTopLeft => top_left, :inputTopRight => top_right, :inputBottomLeft => bottom_left, :inputBottomRight => bottom_right do |transformed| 10 | @target = transformed 11 | end 12 | end 13 | 14 | def perspective_tiled(top_left, top_right, bottom_left, bottom_right) 15 | create_core_image_context(@original.extent.size.width, @original.extent.size.height) 16 | 17 | @original.perspective_tile :inputTopLeft => top_left, :inputTopRight => top_right, :inputBottomLeft => bottom_left, :inputBottomRight => bottom_right do |tiled| 18 | @target = tiled 19 | end 20 | end 21 | 22 | end 23 | end 24 | end 25 | end -------------------------------------------------------------------------------- /test/processors/image_science_test.rb: -------------------------------------------------------------------------------- 1 | require File.expand_path(File.join(File.dirname(__FILE__), '..', 'test_helper')) 2 | 3 | class ImageScienceTest < Test::Unit::TestCase 4 | attachment_model ImageScienceAttachment 5 | 6 | if Object.const_defined?(:ImageScience) 7 | def test_should_resize_image 8 | attachment = upload_file :filename => '/files/rails.png' 9 | assert_valid attachment 10 | assert attachment.image? 11 | # test image science thumbnail 12 | assert_equal 42, attachment.width 13 | assert_equal 55, attachment.height 14 | 15 | thumb = attachment.thumbnails.detect { |t| t.filename =~ /_thumb/ } 16 | geo = attachment.thumbnails.detect { |t| t.filename =~ /_geometry/ } 17 | 18 | # test exact resize dimensions 19 | assert_equal 50, thumb.width 20 | assert_equal 51, thumb.height 21 | 22 | # test geometry string 23 | assert_equal 31, geo.width 24 | assert_equal 41, geo.height 25 | end 26 | else 27 | def test_flunk 28 | puts "ImageScience not loaded, tests not running" 29 | end 30 | end 31 | end -------------------------------------------------------------------------------- /vendor/red_artisan/core_image/filters/effects.rb: -------------------------------------------------------------------------------- 1 | module RedArtisan 2 | module CoreImage 3 | module Filters 4 | module Effects 5 | 6 | def spotlight(position, points_at, brightness, concentration, color) 7 | create_core_image_context(@original.extent.size.width, @original.extent.size.height) 8 | 9 | @original.spot_light :inputLightPosition => vector3(*position), :inputLightPointsAt => vector3(*points_at), 10 | :inputBrightness => brightness, :inputConcentration => concentration, :inputColor => color do |spot| 11 | @target = spot 12 | end 13 | end 14 | 15 | def edges(intensity = 1.00) 16 | create_core_image_context(@original.extent.size.width, @original.extent.size.height) 17 | 18 | @original.edges :inputIntensity => intensity do |edged| 19 | @target = edged 20 | end 21 | end 22 | 23 | private 24 | 25 | def vector3(x, y, w) 26 | OSX::CIVector.vectorWithX_Y_Z(x, y, w) 27 | end 28 | end 29 | end 30 | end 31 | end 32 | -------------------------------------------------------------------------------- /vendor/red_artisan/core_image/filters/watermark.rb: -------------------------------------------------------------------------------- 1 | module RedArtisan 2 | module CoreImage 3 | module Filters 4 | module Watermark 5 | 6 | def watermark(watermark_image, tile = false, strength = 0.1) 7 | create_core_image_context(@original.extent.size.width, @original.extent.size.height) 8 | 9 | if watermark_image.respond_to? :to_str 10 | watermark_image = OSX::CIImage.from(watermark_image.to_str) 11 | end 12 | 13 | if tile 14 | tile_transform = OSX::NSAffineTransform.transform 15 | tile_transform.scaleXBy_yBy 1.0, 1.0 16 | 17 | watermark_image.affine_tile :inputTransform => tile_transform do |tiled| 18 | tiled.crop :inputRectangle => vector(0, 0, @original.extent.size.width, @original.extent.size.height) do |tiled_watermark| 19 | watermark_image = tiled_watermark 20 | end 21 | end 22 | end 23 | 24 | @original.dissolve_transition :inputTargetImage => watermark_image, :inputTime => strength do |watermarked| 25 | @target = watermarked 26 | end 27 | end 28 | 29 | end 30 | end 31 | end 32 | end -------------------------------------------------------------------------------- /test/processors/core_image_test.rb: -------------------------------------------------------------------------------- 1 | require File.expand_path(File.join(File.dirname(__FILE__), '..', 'test_helper')) 2 | 3 | class CoreImageTest < Test::Unit::TestCase 4 | attachment_model CoreImageAttachment 5 | 6 | if Object.const_defined?(:OSX) 7 | def test_should_resize_image 8 | attachment = upload_file :filename => '/files/rails.png' 9 | assert_valid attachment 10 | assert attachment.image? 11 | # test core image thumbnail 12 | assert_equal 42, attachment.width 13 | assert_equal 55, attachment.height 14 | 15 | thumb = attachment.thumbnails.detect { |t| t.filename =~ /_thumb/ } 16 | geo = attachment.thumbnails.detect { |t| t.filename =~ /_geometry/ } 17 | 18 | # test exact resize dimensions 19 | assert_equal 50, thumb.width 20 | assert_equal 51, thumb.height 21 | 22 | # test geometry string 23 | assert_equal 31, geo.width 24 | assert_equal 41, geo.height 25 | 26 | # This makes sure that we didn't overwrite the original file 27 | # and will end up with a thumbnail instead of the original 28 | assert_equal 42, attachment.width 29 | assert_equal 55, attachment.height 30 | 31 | end 32 | else 33 | def test_flunk 34 | puts "CoreImage not loaded, tests not running" 35 | end 36 | end 37 | end -------------------------------------------------------------------------------- /lib/technoweenie/attachment_fu/backends/db_file_backend.rb: -------------------------------------------------------------------------------- 1 | module Technoweenie # :nodoc: 2 | module AttachmentFu # :nodoc: 3 | module Backends 4 | # Methods for DB backed attachments 5 | module DbFileBackend 6 | def self.included(base) #:nodoc: 7 | Object.const_set(:DbFile, Class.new(ActiveRecord::Base)) unless Object.const_defined?(:DbFile) 8 | base.belongs_to :db_file, :class_name => '::DbFile', :foreign_key => 'db_file_id' 9 | end 10 | 11 | # Creates a temp file with the current db data. 12 | def create_temp_file 13 | write_to_temp_file current_data 14 | end 15 | 16 | # Gets the current data from the database 17 | def current_data 18 | db_file.data 19 | end 20 | 21 | protected 22 | # Destroys the file. Called in the after_destroy callback 23 | def destroy_file 24 | db_file.destroy if db_file 25 | end 26 | 27 | # Saves the data to the DbFile model 28 | def save_to_storage 29 | if save_attachment? 30 | (db_file || build_db_file).data = temp_data 31 | db_file.save! 32 | self.class.update_all ['db_file_id = ?', self.db_file_id = db_file.id], ['id = ?', id] 33 | end 34 | true 35 | end 36 | end 37 | end 38 | end 39 | end -------------------------------------------------------------------------------- /vendor/red_artisan/core_image/filters/scale.rb: -------------------------------------------------------------------------------- 1 | module RedArtisan 2 | module CoreImage 3 | module Filters 4 | module Scale 5 | 6 | def resize(width, height) 7 | create_core_image_context(width, height) 8 | 9 | scale_x, scale_y = scale(width, height) 10 | 11 | @original.affine_clamp :inputTransform => OSX::NSAffineTransform.transform do |clamped| 12 | clamped.lanczos_scale_transform :inputScale => scale_x > scale_y ? scale_x : scale_y, :inputAspectRatio => scale_x / scale_y do |scaled| 13 | scaled.crop :inputRectangle => vector(0, 0, width, height) do |cropped| 14 | @target = cropped 15 | end 16 | end 17 | end 18 | end 19 | 20 | def thumbnail(width, height) 21 | create_core_image_context(width, height) 22 | 23 | transform = OSX::NSAffineTransform.transform 24 | transform.scaleXBy_yBy *scale(width, height) 25 | 26 | @original.affine_transform :inputTransform => transform do |scaled| 27 | @target = scaled 28 | end 29 | end 30 | 31 | def fit(size) 32 | original_size = @original.extent.size 33 | scale = size.to_f / (original_size.width > original_size.height ? original_size.width : original_size.height) 34 | resize (original_size.width * scale).to_i, (original_size.height * scale).to_i 35 | end 36 | 37 | private 38 | 39 | def scale(width, height) 40 | original_size = @original.extent.size 41 | return width.to_f / original_size.width.to_f, height.to_f / original_size.height.to_f 42 | end 43 | 44 | end 45 | end 46 | end 47 | end -------------------------------------------------------------------------------- /CHANGELOG: -------------------------------------------------------------------------------- 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] 36 | -------------------------------------------------------------------------------- /test/validation_test.rb: -------------------------------------------------------------------------------- 1 | require File.expand_path(File.join(File.dirname(__FILE__), 'test_helper')) 2 | 3 | class ValidationTest < Test::Unit::TestCase 4 | def test_should_invalidate_big_files 5 | @attachment = SmallAttachment.new 6 | assert !@attachment.valid? 7 | assert @attachment.errors.on(:size) 8 | 9 | @attachment.size = 2000 10 | assert !@attachment.valid? 11 | assert @attachment.errors.on(:size), @attachment.errors.full_messages.to_sentence 12 | 13 | @attachment.size = 1000 14 | assert !@attachment.valid? 15 | assert_nil @attachment.errors.on(:size) 16 | end 17 | 18 | def test_should_invalidate_small_files 19 | @attachment = BigAttachment.new 20 | assert !@attachment.valid? 21 | assert @attachment.errors.on(:size) 22 | 23 | @attachment.size = 2000 24 | assert !@attachment.valid? 25 | assert @attachment.errors.on(:size), @attachment.errors.full_messages.to_sentence 26 | 27 | @attachment.size = 1.megabyte 28 | assert !@attachment.valid? 29 | assert_nil @attachment.errors.on(:size) 30 | end 31 | 32 | def test_should_validate_content_type 33 | @attachment = PdfAttachment.new 34 | assert !@attachment.valid? 35 | assert @attachment.errors.on(:content_type) 36 | 37 | @attachment.content_type = 'foo' 38 | assert !@attachment.valid? 39 | assert @attachment.errors.on(:content_type) 40 | 41 | @attachment.content_type = 'pdf' 42 | assert !@attachment.valid? 43 | assert_nil @attachment.errors.on(:content_type) 44 | end 45 | 46 | def test_should_require_filename 47 | @attachment = Attachment.new 48 | assert !@attachment.valid? 49 | assert @attachment.errors.on(:filename) 50 | 51 | @attachment.filename = 'foo' 52 | assert !@attachment.valid? 53 | assert_nil @attachment.errors.on(:filename) 54 | end 55 | end -------------------------------------------------------------------------------- /lib/technoweenie/attachment_fu/processors/gd2_processor.rb: -------------------------------------------------------------------------------- 1 | require 'rubygems' 2 | require 'gd2' 3 | module Technoweenie # :nodoc: 4 | module AttachmentFu # :nodoc: 5 | module Processors 6 | module Gd2Processor 7 | def self.included(base) 8 | base.send :extend, ClassMethods 9 | base.alias_method_chain :process_attachment, :processing 10 | end 11 | 12 | module ClassMethods 13 | # Yields a block containing a GD2 Image for the given binary data. 14 | def with_image(file, &block) 15 | im = GD2::Image.import(file) 16 | block.call(im) 17 | end 18 | end 19 | 20 | protected 21 | def process_attachment_with_processing 22 | return unless process_attachment_without_processing && image? 23 | with_image do |img| 24 | resize_image_or_thumbnail! img 25 | self.width = img.width 26 | self.height = img.height 27 | callback_with_args :after_resize, img 28 | end 29 | end 30 | 31 | # Performs the actual resizing operation for a thumbnail 32 | def resize_image(img, size) 33 | size = size.first if size.is_a?(Array) && size.length == 1 34 | if size.is_a?(Fixnum) || (size.is_a?(Array) && size.first.is_a?(Fixnum)) 35 | if size.is_a?(Fixnum) 36 | # Borrowed from image science's #thumbnail method and adapted 37 | # for this. 38 | scale = size.to_f / (img.width > img.height ? img.width.to_f : img.height.to_f) 39 | img.resize!((img.width * scale).round(1), (img.height * scale).round(1), false) 40 | else 41 | img.resize!(size.first, size.last, false) 42 | end 43 | else 44 | w, h = [img.width, img.height] / size.to_s 45 | img.resize!(w, h, false) 46 | end 47 | temp_paths.unshift random_tempfile_filename 48 | self.size = img.export(self.temp_path) 49 | end 50 | 51 | end 52 | end 53 | end 54 | end -------------------------------------------------------------------------------- /lib/technoweenie/attachment_fu/processors/core_image_processor.rb: -------------------------------------------------------------------------------- 1 | require 'red_artisan/core_image/processor' 2 | 3 | module Technoweenie # :nodoc: 4 | module AttachmentFu # :nodoc: 5 | module Processors 6 | module CoreImageProcessor 7 | def self.included(base) 8 | base.send :extend, ClassMethods 9 | base.alias_method_chain :process_attachment, :processing 10 | end 11 | 12 | module ClassMethods 13 | def with_image(file, &block) 14 | block.call OSX::CIImage.from(file) 15 | end 16 | end 17 | 18 | protected 19 | def process_attachment_with_processing 20 | return unless process_attachment_without_processing 21 | with_image do |img| 22 | self.width = img.extent.size.width if respond_to?(:width) 23 | self.height = img.extent.size.height if respond_to?(:height) 24 | resize_image_or_thumbnail! img 25 | callback_with_args :after_resize, img 26 | end if image? 27 | end 28 | 29 | # Performs the actual resizing operation for a thumbnail 30 | def resize_image(img, size) 31 | processor = ::RedArtisan::CoreImage::Processor.new(img) 32 | size = size.first if size.is_a?(Array) && size.length == 1 33 | if size.is_a?(Fixnum) || (size.is_a?(Array) && size.first.is_a?(Fixnum)) 34 | if size.is_a?(Fixnum) 35 | processor.fit(size) 36 | else 37 | processor.resize(size[0], size[1]) 38 | end 39 | else 40 | new_size = [img.extent.size.width, img.extent.size.height] / size.to_s 41 | processor.resize(new_size[0], new_size[1]) 42 | end 43 | 44 | processor.render do |result| 45 | self.width = result.extent.size.width if respond_to?(:width) 46 | self.height = result.extent.size.height if respond_to?(:height) 47 | 48 | # Get a new temp_path for the image before saving 49 | temp_paths.unshift Tempfile.new(random_tempfile_filename, Technoweenie::AttachmentFu.tempfile_path).path 50 | result.save self.temp_path, OSX::NSJPEGFileType 51 | self.size = File.size(self.temp_path) 52 | end 53 | end 54 | end 55 | end 56 | end 57 | end 58 | 59 | 60 | -------------------------------------------------------------------------------- /test/extra_attachment_test.rb: -------------------------------------------------------------------------------- 1 | require File.expand_path(File.join(File.dirname(__FILE__), 'test_helper')) 2 | 3 | class OrphanAttachmentTest < Test::Unit::TestCase 4 | include BaseAttachmentTests 5 | attachment_model OrphanAttachment 6 | 7 | def test_should_create_image_from_uploaded_file 8 | assert_created do 9 | attachment = upload_file :filename => '/files/rails.png' 10 | assert_valid attachment 11 | assert !attachment.db_file.new_record? if attachment.respond_to?(:db_file) 12 | assert attachment.image? 13 | assert !attachment.size.zero? 14 | end 15 | end 16 | 17 | def test_should_create_file_from_uploaded_file 18 | assert_created do 19 | attachment = upload_file :filename => '/files/foo.txt' 20 | assert_valid attachment 21 | assert !attachment.db_file.new_record? if attachment.respond_to?(:db_file) 22 | assert attachment.image? 23 | assert !attachment.size.zero? 24 | end 25 | end 26 | 27 | def test_should_create_file_from_merb_temp_file 28 | assert_created do 29 | attachment = upload_merb_file :filename => '/files/foo.txt' 30 | assert_valid attachment 31 | assert !attachment.db_file.new_record? if attachment.respond_to?(:db_file) 32 | assert attachment.image? 33 | assert !attachment.size.zero? 34 | end 35 | end 36 | 37 | def test_should_create_image_from_uploaded_file_with_custom_content_type 38 | assert_created do 39 | attachment = upload_file :content_type => 'foo/bar', :filename => '/files/rails.png' 40 | assert_valid attachment 41 | assert !attachment.image? 42 | assert !attachment.db_file.new_record? if attachment.respond_to?(:db_file) 43 | assert !attachment.size.zero? 44 | #assert_equal 1784, attachment.size 45 | end 46 | end 47 | 48 | def test_should_create_thumbnail 49 | attachment = upload_file :filename => '/files/rails.png' 50 | 51 | assert_raise Technoweenie::AttachmentFu::ThumbnailError do 52 | attachment.create_or_update_thumbnail(attachment.create_temp_file, 'thumb', 50, 50) 53 | end 54 | end 55 | 56 | def test_should_create_thumbnail_with_geometry_string 57 | attachment = upload_file :filename => '/files/rails.png' 58 | 59 | assert_raise Technoweenie::AttachmentFu::ThumbnailError do 60 | attachment.create_or_update_thumbnail(attachment.create_temp_file, 'thumb', 'x50') 61 | end 62 | end 63 | end 64 | 65 | class MinimalAttachmentTest < OrphanAttachmentTest 66 | attachment_model MinimalAttachment 67 | end -------------------------------------------------------------------------------- /lib/technoweenie/attachment_fu/processors/image_science_processor.rb: -------------------------------------------------------------------------------- 1 | require 'image_science' 2 | module Technoweenie # :nodoc: 3 | module AttachmentFu # :nodoc: 4 | module Processors 5 | module ImageScienceProcessor 6 | def self.included(base) 7 | base.send :extend, ClassMethods 8 | base.alias_method_chain :process_attachment, :processing 9 | end 10 | 11 | module ClassMethods 12 | # Yields a block containing an Image Science image for the given binary data. 13 | def with_image(file, &block) 14 | ::ImageScience.with_image file, &block 15 | end 16 | end 17 | 18 | protected 19 | def process_attachment_with_processing 20 | return unless process_attachment_without_processing && image? 21 | with_image do |img| 22 | self.width = img.width if respond_to?(:width) 23 | self.height = img.height if respond_to?(:height) 24 | resize_image_or_thumbnail! img 25 | end 26 | end 27 | 28 | # Performs the actual resizing operation for a thumbnail 29 | def resize_image(img, size) 30 | # create a dummy temp file to write to 31 | # ImageScience doesn't handle all gifs properly, so it converts them to 32 | # pngs for thumbnails. It has something to do with trying to save gifs 33 | # with a larger palette than 256 colors, which is all the gif format 34 | # supports. 35 | filename.sub! /gif$/, 'png' 36 | content_type.sub!(/gif$/, 'png') 37 | temp_paths.unshift write_to_temp_file(filename) 38 | grab_dimensions = lambda do |img| 39 | self.width = img.width if respond_to?(:width) 40 | self.height = img.height if respond_to?(:height) 41 | img.save self.temp_path 42 | self.size = File.size(self.temp_path) 43 | callback_with_args :after_resize, img 44 | end 45 | 46 | size = size.first if size.is_a?(Array) && size.length == 1 47 | if size.is_a?(Fixnum) || (size.is_a?(Array) && size.first.is_a?(Fixnum)) 48 | if size.is_a?(Fixnum) 49 | img.thumbnail(size, &grab_dimensions) 50 | else 51 | img.resize(size[0], size[1], &grab_dimensions) 52 | end 53 | else 54 | new_size = [img.width, img.height] / size.to_s 55 | img.resize(new_size[0], new_size[1], &grab_dimensions) 56 | end 57 | end 58 | end 59 | end 60 | end 61 | end -------------------------------------------------------------------------------- /test/base_attachment_tests.rb: -------------------------------------------------------------------------------- 1 | module BaseAttachmentTests 2 | def test_should_create_file_from_uploaded_file 3 | assert_created do 4 | attachment = upload_file :filename => '/files/foo.txt' 5 | assert_valid attachment 6 | assert !attachment.db_file.new_record? if attachment.respond_to?(:db_file) 7 | assert attachment.image? 8 | assert !attachment.size.zero? 9 | #assert_equal 3, attachment.size 10 | assert_nil attachment.width 11 | assert_nil attachment.height 12 | end 13 | end 14 | 15 | def test_should_create_file_from_merb_temp_file 16 | assert_created do 17 | attachment = upload_merb_file :filename => '/files/foo.txt' 18 | assert_valid attachment 19 | assert !attachment.db_file.new_record? if attachment.respond_to?(:db_file) 20 | assert attachment.image? 21 | assert !attachment.size.zero? 22 | #assert_equal 3, attachment.size 23 | assert_nil attachment.width 24 | assert_nil attachment.height 25 | end 26 | end 27 | 28 | def test_reassign_attribute_data 29 | assert_created 1 do 30 | attachment = upload_file :filename => '/files/rails.png' 31 | assert_valid attachment 32 | assert attachment.size > 0, "no data was set" 33 | 34 | attachment.set_temp_data 'wtf' 35 | assert attachment.save_attachment? 36 | attachment.save! 37 | 38 | assert_equal 'wtf', attachment_model.find(attachment.id).send(:current_data) 39 | end 40 | end 41 | 42 | def test_no_reassign_attribute_data_on_nil 43 | assert_created 1 do 44 | attachment = upload_file :filename => '/files/rails.png' 45 | assert_valid attachment 46 | assert attachment.size > 0, "no data was set" 47 | 48 | attachment.set_temp_data nil 49 | assert !attachment.save_attachment? 50 | end 51 | end 52 | 53 | def test_should_overwrite_old_contents_when_updating 54 | attachment = upload_file :filename => '/files/rails.png' 55 | assert_not_created do # no new db_file records 56 | use_temp_file 'files/rails.png' do |file| 57 | attachment.filename = 'rails2.png' 58 | attachment.temp_paths.unshift File.join(fixture_path, file) 59 | attachment.save! 60 | end 61 | end 62 | end 63 | 64 | def test_should_save_without_updating_file 65 | attachment = upload_file :filename => '/files/foo.txt' 66 | assert_valid attachment 67 | assert !attachment.save_attachment? 68 | assert_nothing_raised { attachment.save! } 69 | end 70 | 71 | def test_should_handle_nil_file_upload 72 | attachment = attachment_model.create :uploaded_data => '' 73 | assert_raise ActiveRecord::RecordInvalid do 74 | attachment.save! 75 | end 76 | end 77 | end -------------------------------------------------------------------------------- /lib/technoweenie/attachment_fu/processors/rmagick_processor.rb: -------------------------------------------------------------------------------- 1 | require 'RMagick' 2 | module Technoweenie # :nodoc: 3 | module AttachmentFu # :nodoc: 4 | module Processors 5 | module RmagickProcessor 6 | def self.included(base) 7 | base.send :extend, ClassMethods 8 | base.alias_method_chain :process_attachment, :processing 9 | end 10 | 11 | module ClassMethods 12 | # Yields a block containing an RMagick Image for the given binary data. 13 | def with_image(file, &block) 14 | begin 15 | binary_data = file.is_a?(Magick::Image) ? file : Magick::Image.read(file).first unless !Object.const_defined?(:Magick) 16 | rescue 17 | # Log the failure to load the image. This should match ::Magick::ImageMagickError 18 | # but that would cause acts_as_attachment to require rmagick. 19 | logger.debug("Exception working with image: #{$!}") 20 | binary_data = nil 21 | end 22 | block.call binary_data if block && binary_data 23 | ensure 24 | !binary_data.nil? 25 | end 26 | end 27 | 28 | protected 29 | def process_attachment_with_processing 30 | return unless process_attachment_without_processing 31 | with_image do |img| 32 | resize_image_or_thumbnail! img 33 | self.width = img.columns if respond_to?(:width) 34 | self.height = img.rows if respond_to?(:height) 35 | callback_with_args :after_resize, img 36 | end if image? 37 | end 38 | 39 | # Performs the actual resizing operation for a thumbnail 40 | def resize_image(img, size) 41 | size = size.first if size.is_a?(Array) && size.length == 1 && !size.first.is_a?(Fixnum) 42 | if size.is_a?(Fixnum) || (size.is_a?(Array) && size.first.is_a?(Fixnum)) 43 | size = [size, size] if size.is_a?(Fixnum) 44 | img.thumbnail!(*size) 45 | elsif size.is_a?(String) && size =~ /^c.*$/ # Image cropping - example geometry string: c75x75 46 | dimensions = size[1..size.size].split("x") 47 | if respond_to?(:crop_x) 48 | img.crop!(self.crop_x, self.crop_y, self.crop_width, self.crop_height) 49 | img.resize!(dimensions[0].to_i, dimensions[1].to_i) 50 | else 51 | img.crop_resized!(dimensions[0].to_i, dimensions[1].to_i) 52 | end 53 | else 54 | img.change_geometry(size.to_s) { |cols, rows, image| image.resize!(cols<1 ? 1 : cols, rows<1 ? 1 : rows) } 55 | end 56 | img.strip! unless attachment_options[:keep_profile] 57 | temp_paths.unshift write_to_temp_file(img.to_blob) 58 | end 59 | end 60 | end 61 | end 62 | end 63 | -------------------------------------------------------------------------------- /test/basic_test.rb: -------------------------------------------------------------------------------- 1 | require File.expand_path(File.join(File.dirname(__FILE__), 'test_helper')) 2 | 3 | class BasicTest < Test::Unit::TestCase 4 | def test_should_set_default_min_size 5 | assert_equal 1, Attachment.attachment_options[:min_size] 6 | end 7 | 8 | def test_should_set_default_max_size 9 | assert_equal 1.megabyte, Attachment.attachment_options[:max_size] 10 | end 11 | 12 | def test_should_set_default_size 13 | assert_equal (1..1.megabyte), Attachment.attachment_options[:size] 14 | end 15 | 16 | def test_should_set_default_thumbnails_option 17 | assert_equal Hash.new, Attachment.attachment_options[:thumbnails] 18 | end 19 | 20 | def test_should_set_default_thumbnail_class 21 | assert_equal Attachment, Attachment.attachment_options[:thumbnail_class] 22 | end 23 | 24 | def test_should_normalize_content_types_to_array 25 | assert_equal %w(pdf), PdfAttachment.attachment_options[:content_type] 26 | assert_equal %w(pdf doc txt), DocAttachment.attachment_options[:content_type] 27 | assert_equal Technoweenie::AttachmentFu.content_types, ImageAttachment.attachment_options[:content_type] 28 | assert_equal ['pdf'] + Technoweenie::AttachmentFu.content_types, ImageOrPdfAttachment.attachment_options[:content_type] 29 | end 30 | 31 | def test_should_sanitize_content_type 32 | @attachment = Attachment.new 33 | @attachment.content_type = ' foo ' 34 | assert_equal 'foo', @attachment.content_type 35 | end 36 | 37 | def test_should_sanitize_filenames 38 | @attachment = Attachment.new 39 | @attachment.filename = 'foo.bar' 40 | assert_equal 'foo.bar', @attachment.filename 41 | 42 | @attachment.filename = 'blah\\foo.bar' 43 | assert_equal 'foo.bar', @attachment.filename 44 | 45 | @attachment.filename = 'f o!O-.bar' 46 | assert_equal 'f_o_O-.bar', @attachment.filename 47 | 48 | @attachment.filename = 'sheeps_says_bææ' 49 | assert_equal 'sheeps_says_b__', @attachment.filename 50 | 51 | @attachment.filename = nil 52 | assert_nil @attachment.filename 53 | end 54 | 55 | def test_should_convert_thumbnail_name 56 | @attachment = FileAttachment.new 57 | @attachment.filename = 'foo.bar' 58 | assert_equal 'foo.bar', @attachment.thumbnail_name_for(nil) 59 | assert_equal 'foo.bar', @attachment.thumbnail_name_for('') 60 | assert_equal 'foo_blah.bar', @attachment.thumbnail_name_for(:blah) 61 | assert_equal 'foo_blah.blah.bar', @attachment.thumbnail_name_for('blah.blah') 62 | 63 | @attachment.filename = 'foo.bar.baz' 64 | assert_equal 'foo.bar_blah.baz', @attachment.thumbnail_name_for(:blah) 65 | end 66 | 67 | def test_should_require_valid_thumbnails_option 68 | klass = Class.new(ActiveRecord::Base) 69 | assert_raise ArgumentError do 70 | klass.has_attachment :thumbnails => [] 71 | end 72 | end 73 | end 74 | -------------------------------------------------------------------------------- /test/geometry_test.rb: -------------------------------------------------------------------------------- 1 | require 'test/unit' 2 | require File.expand_path(File.join(File.dirname(__FILE__), '../lib/geometry')) unless Object.const_defined?(:Geometry) 3 | 4 | class GeometryTest < Test::Unit::TestCase 5 | def test_should_resize 6 | assert_geometry 50, 64, 7 | "50x50" => [39, 50], 8 | "60x60" => [47, 60], 9 | "100x100" => [78, 100] 10 | end 11 | 12 | def test_should_resize_no_width 13 | assert_geometry 50, 64, 14 | "x50" => [39, 50], 15 | "x60" => [47, 60], 16 | "x100" => [78, 100] 17 | end 18 | 19 | def test_should_resize_no_height 20 | assert_geometry 50, 64, 21 | "50" => [50, 64], 22 | "60" => [60, 77], 23 | "100" => [100, 128] 24 | end 25 | 26 | def test_should_resize_no_height_with_x 27 | assert_geometry 50, 64, 28 | "50x" => [50, 64], 29 | "60x" => [60, 77], 30 | "100x" => [100, 128] 31 | end 32 | 33 | def test_should_resize_with_percent 34 | assert_geometry 50, 64, 35 | "50x50%" => [25, 32], 36 | "60x60%" => [30, 38], 37 | "120x112%" => [60, 72] 38 | end 39 | 40 | def test_should_resize_with_percent_and_no_width 41 | assert_geometry 50, 64, 42 | "x50%" => [50, 32], 43 | "x60%" => [50, 38], 44 | "x112%" => [50, 72] 45 | end 46 | 47 | def test_should_resize_with_percent_and_no_height 48 | assert_geometry 50, 64, 49 | "50%" => [25, 32], 50 | "60%" => [30, 38], 51 | "120%" => [60, 77] 52 | end 53 | 54 | def test_should_resize_with_less 55 | assert_geometry 50, 64, 56 | "50x50<" => [50, 64], 57 | "60x60<" => [50, 64], 58 | "100x100<" => [78, 100], 59 | "100x112<" => [88, 112], 60 | "40x70<" => [50, 64] 61 | end 62 | 63 | def test_should_resize_with_less_and_no_width 64 | assert_geometry 50, 64, 65 | "x50<" => [50, 64], 66 | "x60<" => [50, 64], 67 | "x100<" => [78, 100] 68 | end 69 | 70 | def test_should_resize_with_less_and_no_height 71 | assert_geometry 50, 64, 72 | "50<" => [50, 64], 73 | "60<" => [60, 77], 74 | "100<" => [100, 128] 75 | end 76 | 77 | def test_should_resize_with_greater 78 | assert_geometry 50, 64, 79 | "50x50>" => [39, 50], 80 | "60x60>" => [47, 60], 81 | "100x100>" => [50, 64], 82 | "100x112>" => [50, 64], 83 | "40x70>" => [40, 51] 84 | end 85 | 86 | def test_should_resize_with_greater_and_no_width 87 | assert_geometry 50, 64, 88 | "x40>" => [31, 40], 89 | "x60>" => [47, 60], 90 | "x100>" => [50, 64] 91 | end 92 | 93 | def test_should_resize_with_greater_and_no_height 94 | assert_geometry 50, 64, 95 | "40>" => [40, 51], 96 | "60>" => [50, 64], 97 | "100>" => [50, 64] 98 | end 99 | 100 | protected 101 | def assert_geometry(width, height, values) 102 | values.each do |geo, result| 103 | # run twice to verify the Geometry string isn't modified after a run 104 | geo = Geometry.from_s(geo) 105 | 2.times { assert_equal result, [width, height] / geo } 106 | end 107 | end 108 | end -------------------------------------------------------------------------------- /lib/geometry.rb: -------------------------------------------------------------------------------- 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 94 | -------------------------------------------------------------------------------- /test/processors/mini_magick_test.rb: -------------------------------------------------------------------------------- 1 | require File.expand_path(File.join(File.dirname(__FILE__), '..', 'test_helper')) 2 | 3 | class MiniMagickTest < Test::Unit::TestCase 4 | attachment_model MiniMagickAttachment 5 | 6 | if Object.const_defined?(:MiniMagick) 7 | def test_should_resize_image 8 | attachment = upload_file :filename => '/files/rails.png' 9 | assert_valid attachment 10 | assert attachment.image? 11 | # test MiniMagick thumbnail 12 | assert_equal 43, attachment.width 13 | assert_equal 55, attachment.height 14 | 15 | thumb = attachment.thumbnails.detect { |t| t.filename =~ /_thumb/ } 16 | geo = attachment.thumbnails.detect { |t| t.filename =~ /_geometry/ } 17 | 18 | # test exact resize dimensions 19 | assert_equal 50, thumb.width 20 | assert_equal 51, thumb.height 21 | 22 | # test geometry string 23 | assert_equal 31, geo.width 24 | assert_equal 40, geo.height 25 | end 26 | 27 | def test_should_crop_image(klass = ImageThumbnailCrop) 28 | attachment_model klass 29 | attachment = upload_file :filename => '/files/rails.png' 30 | assert_valid attachment 31 | assert attachment.image? 32 | # has_attachment :thumbnails => { :square => "50x50c", :vertical => "30x60c", :horizontal => "60x30c"} 33 | 34 | square = attachment.thumbnails.detect { |t| t.filename =~ /_square/ } 35 | vertical = attachment.thumbnails.detect { |t| t.filename =~ /_vertical/ } 36 | horizontal = attachment.thumbnails.detect { |t| t.filename =~ /_horizontal/ } 37 | 38 | # test excat resize 39 | assert_equal 50, square.width 40 | assert_equal 50, square.height 41 | 42 | assert_equal 30, vertical.width 43 | assert_equal 60, vertical.height 44 | 45 | assert_equal 60, horizontal.width 46 | assert_equal 30, horizontal.height 47 | end 48 | 49 | # tests the first step in resize, crop the image in original size to right format 50 | def test_should_crop_image_right(klass = ImageThumbnailCrop) 51 | @@testcases.collect do |testcase| 52 | image_width, image_height, thumb_width, thumb_height = testcase[:data] 53 | image_aspect, thumb_aspect = image_width/image_height, thumb_width/thumb_height 54 | crop_comand = klass.calculate_offset(image_width, image_height, image_aspect, thumb_width, thumb_height,thumb_aspect) 55 | # pattern matching on crop command 56 | if testcase.has_key?(:height) 57 | assert crop_comand.match(/^#{image_width}x#{testcase[:height]}\+0\+#{testcase[:yoffset]}$/) 58 | else 59 | assert crop_comand.match(/^#{testcase[:width]}x#{image_height}\+#{testcase[:xoffset]}\+0$/) 60 | end 61 | end 62 | end 63 | 64 | else 65 | def test_flunk 66 | puts "MiniMagick not loaded, tests not running" 67 | end 68 | end 69 | 70 | @@testcases = [ 71 | # image_aspect <= 1 && thumb_aspect >= 1 72 | {:data => [10.0,40.0,2.0,1.0], :height => 5.0, :yoffset => 17.5}, # 1b 73 | {:data => [10.0,40.0,1.0,1.0], :height => 10.0, :yoffset => 15.0}, # 1b 74 | 75 | # image_aspect < 1 && thumb_aspect < 1 76 | {:data => [10.0,40.0,1.0,2.0], :height => 20.0, :yoffset => 10.0}, # 1a 77 | {:data => [2.0,3.0,1.0,2.0], :width => 1.5, :xoffset => 0.25}, # 1a 78 | 79 | # image_aspect = thumb_aspect 80 | {:data => [10.0,10.0,1.0,1.0], :height => 10.0, :yoffset => 0.0}, # QUADRAT 1c 81 | 82 | # image_aspect >= 1 && thumb_aspect > 1 && image_aspect < thumb_aspect 83 | {:data => [6.0,3.0,4.0,1.0], :height => 1.5, :yoffset => 0.75}, # 2b 84 | {:data => [6.0,6.0,4.0,1.0], :height => 1.5, :yoffset => 2.25}, # 2b 85 | 86 | # image_aspect > 1 && thumb_aspect > 1 && image_aspect > thumb_aspect 87 | {:data => [9.0,3.0,2.0,1.0], :width => 6.0, :xoffset => 1.5}, # 2a 88 | 89 | # image_aspect > 1 && thumb_aspect < 1 && image_aspect < thumb_aspect 90 | {:data => [10.0,5.0,0.1,2.0], :width => 0.25, :xoffset => 4.875}, # 4 91 | {:data => [10.0,5.0,1.0,2.0], :width => 2.5, :xoffset => 3.75}, # 4 92 | 93 | # image_aspect > 1 && thumb_aspect > 1 && image_aspect > thumb_aspect 94 | {:data => [9.0,3.0,2.0,1.0], :width => 6.0, :xoffset => 1.5}, # 3a 95 | # image_aspect > 1 && thumb_aspect > 1 && image_aspect < thumb_aspect 96 | {:data => [9.0,3.0,5.0,1.0], :height => 1.8, :yoffset => 0.6} # 3a 97 | ] 98 | 99 | 100 | 101 | 102 | 103 | end 104 | -------------------------------------------------------------------------------- /test/backends/remote/s3_test.rb: -------------------------------------------------------------------------------- 1 | require File.expand_path(File.join(File.dirname(__FILE__), '..', '..', 'test_helper')) 2 | require 'net/http' 3 | 4 | class S3Test < Test::Unit::TestCase 5 | def self.test_S3? 6 | true unless ENV["TEST_S3"] == "false" 7 | end 8 | 9 | if test_S3? && File.exist?(File.join(File.dirname(__FILE__), '../../amazon_s3.yml')) 10 | include BaseAttachmentTests 11 | attachment_model S3Attachment 12 | 13 | def test_should_create_correct_bucket_name(klass = S3Attachment) 14 | attachment_model klass 15 | attachment = upload_file :filename => '/files/rails.png' 16 | assert_equal attachment.s3_config[:bucket_name], attachment.bucket_name 17 | end 18 | 19 | test_against_subclass :test_should_create_correct_bucket_name, S3Attachment 20 | 21 | def test_should_create_default_path_prefix(klass = S3Attachment) 22 | attachment_model klass 23 | attachment = upload_file :filename => '/files/rails.png' 24 | assert_equal File.join(attachment_model.table_name, attachment.attachment_path_id), attachment.base_path 25 | end 26 | 27 | test_against_subclass :test_should_create_default_path_prefix, S3Attachment 28 | 29 | def test_should_create_custom_path_prefix(klass = S3WithPathPrefixAttachment) 30 | attachment_model klass 31 | attachment = upload_file :filename => '/files/rails.png' 32 | assert_equal File.join('some/custom/path/prefix', attachment.attachment_path_id), attachment.base_path 33 | end 34 | 35 | test_against_subclass :test_should_create_custom_path_prefix, S3WithPathPrefixAttachment 36 | 37 | def test_should_create_valid_url(klass = S3Attachment) 38 | attachment_model klass 39 | attachment = upload_file :filename => '/files/rails.png' 40 | assert_equal "#{s3_protocol}#{s3_hostname}#{s3_port_string}/#{attachment.bucket_name}/#{attachment.full_filename}", attachment.s3_url 41 | end 42 | 43 | test_against_subclass :test_should_create_valid_url, S3Attachment 44 | 45 | def test_should_create_authenticated_url(klass = S3Attachment) 46 | attachment_model klass 47 | attachment = upload_file :filename => '/files/rails.png' 48 | assert_match /^http.+AWSAccessKeyId.+Expires.+Signature.+/, attachment.authenticated_s3_url(:use_ssl => true) 49 | end 50 | 51 | test_against_subclass :test_should_create_authenticated_url, S3Attachment 52 | 53 | def test_should_create_authenticated_url_for_thumbnail(klass = S3Attachment) 54 | attachment_model klass 55 | attachment = upload_file :filename => '/files/rails.png' 56 | ['large', :large].each do |thumbnail| 57 | assert_match( 58 | /^http.+rails_large\.png.+AWSAccessKeyId.+Expires.+Signature/, 59 | attachment.authenticated_s3_url(thumbnail), 60 | "authenticated_s3_url failed with #{thumbnail.class} parameter" 61 | ) 62 | end 63 | end 64 | 65 | def test_should_save_attachment(klass = S3Attachment) 66 | attachment_model klass 67 | assert_created do 68 | attachment = upload_file :filename => '/files/rails.png' 69 | assert_valid attachment 70 | assert attachment.image? 71 | assert !attachment.size.zero? 72 | assert_kind_of Net::HTTPOK, http_response_for(attachment.s3_url) 73 | end 74 | end 75 | 76 | test_against_subclass :test_should_save_attachment, S3Attachment 77 | 78 | def test_should_delete_attachment_from_s3_when_attachment_record_destroyed(klass = S3Attachment) 79 | attachment_model klass 80 | attachment = upload_file :filename => '/files/rails.png' 81 | 82 | urls = [attachment.s3_url] + attachment.thumbnails.collect(&:s3_url) 83 | 84 | urls.each {|url| assert_kind_of Net::HTTPOK, http_response_for(url) } 85 | attachment.destroy 86 | urls.each do |url| 87 | begin 88 | http_response_for(url) 89 | rescue Net::HTTPForbidden, Net::HTTPNotFound 90 | nil 91 | end 92 | end 93 | end 94 | 95 | test_against_subclass :test_should_delete_attachment_from_s3_when_attachment_record_destroyed, S3Attachment 96 | 97 | protected 98 | def http_response_for(url) 99 | url = URI.parse(url) 100 | Net::HTTP.start(url.host, url.port) {|http| http.request_head(url.path) } 101 | end 102 | 103 | def s3_protocol 104 | Technoweenie::AttachmentFu::Backends::S3Backend.protocol 105 | end 106 | 107 | def s3_hostname 108 | Technoweenie::AttachmentFu::Backends::S3Backend.hostname 109 | end 110 | 111 | def s3_port_string 112 | Technoweenie::AttachmentFu::Backends::S3Backend.port_string 113 | end 114 | else 115 | def test_flunk_s3 116 | puts "s3 config file not loaded, tests not running" 117 | end 118 | end 119 | end -------------------------------------------------------------------------------- /test/schema.rb: -------------------------------------------------------------------------------- 1 | ActiveRecord::Schema.define(:version => 0) do 2 | create_table :attachments, :force => true do |t| 3 | t.column :db_file_id, :integer 4 | t.column :parent_id, :integer 5 | t.column :thumbnail, :string 6 | t.column :filename, :string, :limit => 255 7 | t.column :content_type, :string, :limit => 255 8 | t.column :size, :integer 9 | t.column :width, :integer 10 | t.column :height, :integer 11 | t.column :aspect_ratio, :float 12 | end 13 | 14 | create_table :file_attachments, :force => true do |t| 15 | t.column :parent_id, :integer 16 | t.column :thumbnail, :string 17 | t.column :filename, :string, :limit => 255 18 | t.column :content_type, :string, :limit => 255 19 | t.column :size, :integer 20 | t.column :width, :integer 21 | t.column :height, :integer 22 | t.column :type, :string 23 | t.column :aspect_ratio, :float 24 | end 25 | 26 | create_table :file_attachments_with_string_id, :id => false, :force => true do |t| 27 | t.column :id, :string 28 | t.column :parent_id, :string 29 | t.column :thumbnail, :string 30 | t.column :filename, :string, :limit => 255 31 | t.column :content_type, :string, :limit => 255 32 | t.column :size, :integer 33 | t.column :width, :integer 34 | t.column :height, :integer 35 | t.column :type, :string 36 | t.column :aspect_ratio, :float 37 | end 38 | 39 | create_table :gd2_attachments, :force => true do |t| 40 | t.column :parent_id, :integer 41 | t.column :thumbnail, :string 42 | t.column :filename, :string, :limit => 255 43 | t.column :content_type, :string, :limit => 255 44 | t.column :size, :integer 45 | t.column :width, :integer 46 | t.column :height, :integer 47 | t.column :type, :string 48 | end 49 | 50 | create_table :image_science_attachments, :force => true do |t| 51 | t.column :parent_id, :integer 52 | t.column :thumbnail, :string 53 | t.column :filename, :string, :limit => 255 54 | t.column :content_type, :string, :limit => 255 55 | t.column :size, :integer 56 | t.column :width, :integer 57 | t.column :height, :integer 58 | t.column :type, :string 59 | end 60 | 61 | create_table :core_image_attachments, :force => true do |t| 62 | t.column :parent_id, :integer 63 | t.column :thumbnail, :string 64 | t.column :filename, :string, :limit => 255 65 | t.column :content_type, :string, :limit => 255 66 | t.column :size, :integer 67 | t.column :width, :integer 68 | t.column :height, :integer 69 | t.column :type, :string 70 | end 71 | 72 | create_table :mini_magick_attachments, :force => true do |t| 73 | t.column :parent_id, :integer 74 | t.column :thumbnail, :string 75 | t.column :filename, :string, :limit => 255 76 | t.column :content_type, :string, :limit => 255 77 | t.column :size, :integer 78 | t.column :width, :integer 79 | t.column :height, :integer 80 | t.column :type, :string 81 | end 82 | 83 | create_table :mini_magick_attachments, :force => true do |t| 84 | t.column :parent_id, :integer 85 | t.column :thumbnail, :string 86 | t.column :filename, :string, :limit => 255 87 | t.column :content_type, :string, :limit => 255 88 | t.column :size, :integer 89 | t.column :width, :integer 90 | t.column :height, :integer 91 | t.column :type, :string 92 | end 93 | 94 | create_table :orphan_attachments, :force => true do |t| 95 | t.column :db_file_id, :integer 96 | t.column :filename, :string, :limit => 255 97 | t.column :content_type, :string, :limit => 255 98 | t.column :size, :integer 99 | end 100 | 101 | create_table :minimal_attachments, :force => true do |t| 102 | t.column :size, :integer 103 | t.column :content_type, :string, :limit => 255 104 | end 105 | 106 | create_table :db_files, :force => true do |t| 107 | t.column :data, :binary 108 | end 109 | 110 | create_table :s3_attachments, :force => true do |t| 111 | t.column :parent_id, :integer 112 | t.column :thumbnail, :string 113 | t.column :filename, :string, :limit => 255 114 | t.column :content_type, :string, :limit => 255 115 | t.column :size, :integer 116 | t.column :width, :integer 117 | t.column :height, :integer 118 | t.column :type, :string 119 | t.column :aspect_ratio, :float 120 | end 121 | end 122 | -------------------------------------------------------------------------------- /vendor/red_artisan/core_image/processor.rb: -------------------------------------------------------------------------------- 1 | require 'rubygems' 2 | require 'osx/cocoa' 3 | require 'active_support' 4 | 5 | require 'red_artisan/core_image/filters/scale' 6 | require 'red_artisan/core_image/filters/color' 7 | require 'red_artisan/core_image/filters/watermark' 8 | require 'red_artisan/core_image/filters/quality' 9 | require 'red_artisan/core_image/filters/perspective' 10 | require 'red_artisan/core_image/filters/effects' 11 | 12 | # Generic image processor for scaling images based on CoreImage via RubyCocoa. 13 | # 14 | # Example usage: 15 | # 16 | # p = Processor.new OSX::CIImage.from(path_to_image) 17 | # p.resize(640, 480) 18 | # p.render do |result| 19 | # result.save('resized.jpg', OSX::NSJPEGFileType) 20 | # end 21 | # 22 | # This will resize the image to the given dimensions exactly, if you'd like to ensure that aspect ratio is preserved: 23 | # 24 | # p = Processor.new OSX::CIImage.from(path_to_image) 25 | # p.fit(640) 26 | # p.render do |result| 27 | # result.save('resized.jpg', OSX::NSJPEGFileType) 28 | # end 29 | # 30 | # fit(size) will attempt its best to resize the image so that the longest width/height (depending on image orientation) will match 31 | # the given size. The second axis will be calculated automatically based on the aspect ratio. 32 | # 33 | # Scaling is performed by first clamping the image so that its external bounds become infinite, this helps when scaling so that any 34 | # rounding discrepencies in dimensions don't affect the resultant image. We then perform a Lanczos transform on the image which scales 35 | # it to the target size. We then crop the image to the traget dimensions. 36 | # 37 | # If you are generating smaller images such as thumbnails where high quality rendering isn't as important, an additional method is 38 | # available: 39 | # 40 | # p = Processor.new OSX::CIImage.from(path_to_image) 41 | # p.thumbnail(100, 100) 42 | # p.render do |result| 43 | # result.save('resized.jpg', OSX::NSJPEGFileType) 44 | # end 45 | # 46 | # This will perform a straight affine transform and scale the X and Y boundaries to the requested size. Generally, this will be faster 47 | # than a lanczos scale transform, but with a scaling quality trade. 48 | # 49 | # More than welcome to intregrate any patches, improvements - feel free to mail me with ideas. 50 | # 51 | # Thanks to 52 | # * Satoshi Nakagawa for working out that OCObjWrapper needs inclusion when aliasing method_missing on existing OSX::* classes. 53 | # * Vasantha Crabb for general help and inspiration with Cocoa 54 | # * Ben Schwarz for example image data and collaboration during performance testing 55 | # 56 | # Copyright (c) Marcus Crafter released under the MIT license 57 | # 58 | module RedArtisan 59 | module CoreImage 60 | class Processor 61 | 62 | def initialize(original) 63 | if original.respond_to? :to_str 64 | @original = OSX::CIImage.from(original.to_str) 65 | else 66 | @original = original 67 | end 68 | end 69 | 70 | def render(&block) 71 | raise "unprocessed image: #{@original}" unless @target 72 | block.call @target 73 | end 74 | 75 | include Filters::Scale, Filters::Color, Filters::Watermark, Filters::Quality, Filters::Perspective, Filters::Effects 76 | 77 | private 78 | 79 | def create_core_image_context(width, height) 80 | output = OSX::NSBitmapImageRep.alloc.initWithBitmapDataPlanes_pixelsWide_pixelsHigh_bitsPerSample_samplesPerPixel_hasAlpha_isPlanar_colorSpaceName_bytesPerRow_bitsPerPixel(nil, width, height, 8, 4, true, false, OSX::NSDeviceRGBColorSpace, 0, 0) 81 | context = OSX::NSGraphicsContext.graphicsContextWithBitmapImageRep(output) 82 | OSX::NSGraphicsContext.setCurrentContext(context) 83 | @ci_context = context.CIContext 84 | end 85 | 86 | def vector(x, y, w, h) 87 | OSX::CIVector.vectorWithX_Y_Z_W(x, y, w, h) 88 | end 89 | end 90 | end 91 | end 92 | 93 | module OSX 94 | class CIImage 95 | include OCObjWrapper 96 | 97 | def method_missing_with_filter_processing(sym, *args, &block) 98 | f = OSX::CIFilter.filterWithName("CI#{sym.to_s.camelize}") 99 | return method_missing_without_filter_processing(sym, *args, &block) unless f 100 | 101 | f.setDefaults if f.respond_to? :setDefaults 102 | f.setValue_forKey(self, 'inputImage') 103 | options = args.last.is_a?(Hash) ? args.last : {} 104 | options.each { |k, v| f.setValue_forKey(v, k.to_s) } 105 | 106 | block.call f.valueForKey('outputImage') 107 | end 108 | 109 | alias_method_chain :method_missing, :filter_processing 110 | 111 | def save(target, format = OSX::NSJPEGFileType, properties = nil) 112 | bitmapRep = OSX::NSBitmapImageRep.alloc.initWithCIImage(self) 113 | blob = bitmapRep.representationUsingType_properties(format, properties) 114 | blob.writeToFile_atomically(target, false) 115 | end 116 | 117 | def self.from(filepath) 118 | raise Errno::ENOENT, "No such file or directory - #{filepath}" unless File.exists?(filepath) 119 | OSX::CIImage.imageWithContentsOfURL(OSX::NSURL.fileURLWithPath(filepath)) 120 | end 121 | end 122 | end 123 | 124 | -------------------------------------------------------------------------------- /test/test_helper.rb: -------------------------------------------------------------------------------- 1 | $:.unshift(File.dirname(__FILE__) + '/../lib') 2 | 3 | ENV['RAILS_ENV'] = 'test' 4 | ENV['RAILS_ROOT'] ||= File.dirname(__FILE__) + '/../../../..' 5 | 6 | require 'test/unit' 7 | require File.expand_path(File.join(ENV['RAILS_ROOT'], 'config/environment.rb')) 8 | require 'active_record/fixtures' 9 | require 'action_controller/test_process' 10 | 11 | config = YAML::load(IO.read(File.dirname(__FILE__) + '/database.yml')) 12 | ActiveRecord::Base.logger = Logger.new(File.dirname(__FILE__) + "/debug.log") 13 | 14 | db_adapter = ENV['DB'] 15 | 16 | # no db passed, try one of these fine config-free DBs before bombing. 17 | db_adapter ||= 18 | begin 19 | require 'rubygems' 20 | require 'sqlite' 21 | 'sqlite' 22 | rescue MissingSourceFile 23 | begin 24 | require 'sqlite3' 25 | 'sqlite3' 26 | rescue MissingSourceFile 27 | end 28 | end 29 | 30 | if db_adapter.nil? 31 | raise "No DB Adapter selected. Pass the DB= option to pick one, or install Sqlite or Sqlite3." 32 | end 33 | 34 | ActiveRecord::Base.establish_connection(config[db_adapter]) 35 | 36 | load(File.dirname(__FILE__) + "/schema.rb") 37 | 38 | Test::Unit::TestCase.fixture_path = File.dirname(__FILE__) + "/fixtures" 39 | $LOAD_PATH.unshift(Test::Unit::TestCase.fixture_path) 40 | 41 | class Test::Unit::TestCase #:nodoc: 42 | include ActionController::TestProcess 43 | def create_fixtures(*table_names) 44 | if block_given? 45 | Fixtures.create_fixtures(Test::Unit::TestCase.fixture_path, table_names) { yield } 46 | else 47 | Fixtures.create_fixtures(Test::Unit::TestCase.fixture_path, table_names) 48 | end 49 | end 50 | 51 | def setup 52 | Attachment.saves = 0 53 | DbFile.transaction { [Attachment, FileAttachment, OrphanAttachment, MinimalAttachment, DbFile].each { |klass| klass.delete_all } } 54 | attachment_model self.class.attachment_model 55 | end 56 | 57 | def teardown 58 | FileUtils.rm_rf File.join(File.dirname(__FILE__), 'files') 59 | end 60 | 61 | self.use_transactional_fixtures = true 62 | self.use_instantiated_fixtures = false 63 | 64 | def self.attachment_model(klass = nil) 65 | @attachment_model = klass if klass 66 | @attachment_model 67 | end 68 | 69 | def self.test_against_class(test_method, klass, subclass = false) 70 | define_method("#{test_method}_on_#{:sub if subclass}class") do 71 | klass = Class.new(klass) if subclass 72 | attachment_model klass 73 | send test_method, klass 74 | end 75 | end 76 | 77 | def self.test_against_subclass(test_method, klass) 78 | test_against_class test_method, klass, true 79 | end 80 | 81 | protected 82 | def upload_file(options = {}) 83 | use_temp_file options[:filename] do |file| 84 | att = attachment_model.create :uploaded_data => fixture_file_upload(file, options[:content_type] || 'image/png') 85 | att.reload unless att.new_record? 86 | return att 87 | end 88 | end 89 | 90 | def upload_merb_file(options = {}) 91 | use_temp_file options[:filename] do |file| 92 | att = attachment_model.create :uploaded_data => {"size" => file.size, "content_type" => options[:content_type] || 'image/png', "filename" => file, 'tempfile' => fixture_file_upload(file, options[:content_type] || 'image/png')} 93 | att.reload unless att.new_record? 94 | return att 95 | end 96 | end 97 | 98 | def use_temp_file(fixture_filename) 99 | temp_path = File.join('/tmp', File.basename(fixture_filename)) 100 | FileUtils.mkdir_p File.join(fixture_path, 'tmp') 101 | FileUtils.cp File.join(fixture_path, fixture_filename), File.join(fixture_path, temp_path) 102 | yield temp_path 103 | ensure 104 | FileUtils.rm_rf File.join(fixture_path, 'tmp') 105 | end 106 | 107 | def assert_created(num = 1) 108 | assert_difference attachment_model.base_class, :count, num do 109 | if attachment_model.included_modules.include? DbFile 110 | assert_difference DbFile, :count, num do 111 | yield 112 | end 113 | else 114 | yield 115 | end 116 | end 117 | end 118 | 119 | def assert_not_created 120 | assert_created(0) { yield } 121 | end 122 | 123 | def should_reject_by_size_with(klass) 124 | attachment_model klass 125 | assert_not_created do 126 | attachment = upload_file :filename => '/files/rails.png' 127 | assert attachment.new_record? 128 | assert attachment.errors.on(:size) 129 | assert_nil attachment.db_file if attachment.respond_to?(:db_file) 130 | end 131 | end 132 | 133 | def assert_difference(object, method = nil, difference = 1) 134 | initial_value = object.send(method) 135 | yield 136 | assert_equal initial_value + difference, object.send(method) 137 | end 138 | 139 | def assert_no_difference(object, method, &block) 140 | assert_difference object, method, 0, &block 141 | end 142 | 143 | def attachment_model(klass = nil) 144 | @attachment_model = klass if klass 145 | @attachment_model 146 | end 147 | end 148 | 149 | require File.join(File.dirname(__FILE__), 'fixtures/attachment') 150 | require File.join(File.dirname(__FILE__), 'base_attachment_tests') -------------------------------------------------------------------------------- /lib/technoweenie/attachment_fu/backends/file_system_backend.rb: -------------------------------------------------------------------------------- 1 | require 'fileutils' 2 | require 'digest/sha2' 3 | 4 | module Technoweenie # :nodoc: 5 | module AttachmentFu # :nodoc: 6 | module Backends 7 | # Methods for file system backed attachments 8 | module FileSystemBackend 9 | def self.included(base) #:nodoc: 10 | base.before_update :rename_file 11 | end 12 | 13 | # Gets the full path to the filename in this format: 14 | # 15 | # # This assumes a model name like MyModel 16 | # # public/#{table_name} is the default filesystem path 17 | # RAILS_ROOT/public/my_models/5/blah.jpg 18 | # 19 | # Overwrite this method in your model to customize the filename. 20 | # The optional thumbnail argument will output the thumbnail's filename. 21 | def full_filename(thumbnail = nil) 22 | file_system_path = (thumbnail ? thumbnail_class : self).attachment_options[:path_prefix].to_s 23 | File.join(RAILS_ROOT, file_system_path, *partitioned_path(thumbnail_name_for(thumbnail))) 24 | end 25 | 26 | # Used as the base path that #public_filename strips off full_filename to create the public path 27 | def base_path 28 | @base_path ||= File.join(RAILS_ROOT, 'public') 29 | end 30 | 31 | # The attachment ID used in the full path of a file 32 | def attachment_path_id 33 | ((respond_to?(:parent_id) && parent_id) || id) || 0 34 | end 35 | 36 | # Partitions the given path into an array of path components. 37 | # 38 | # For example, given an *args of ["foo", "bar"], it will return 39 | # ["0000", "0001", "foo", "bar"] (assuming that that id returns 1). 40 | # 41 | # If the id is not an integer, then path partitioning will be performed by 42 | # hashing the string value of the id with SHA-512, and splitting the result 43 | # into 4 components. If the id a 128-bit UUID (as set by :uuid_primary_key => true) 44 | # then it will be split into 2 components. 45 | # 46 | # To turn this off entirely, set :partition => false. 47 | def partitioned_path(*args) 48 | if respond_to?(:attachment_options) && attachment_options[:partition] == false 49 | args 50 | elsif attachment_options[:uuid_primary_key] 51 | # Primary key is a 128-bit UUID in hex format. Split it into 2 components. 52 | path_id = attachment_path_id.to_s 53 | component1 = path_id[0..15] || "-" 54 | component2 = path_id[16..-1] || "-" 55 | [component1, component2] + args 56 | else 57 | path_id = attachment_path_id 58 | if path_id.is_a?(Integer) 59 | # Primary key is an integer. Split it after padding it with 0. 60 | ("%08d" % path_id).scan(/..../) + args 61 | else 62 | # Primary key is a String. Hash it, then split it into 4 components. 63 | hash = Digest::SHA512.hexdigest(path_id.to_s) 64 | [hash[0..31], hash[32..63], hash[64..95], hash[96..127]] + args 65 | end 66 | end 67 | end 68 | 69 | # Gets the public path to the file 70 | # The optional thumbnail argument will output the thumbnail's filename. 71 | def public_filename(thumbnail = nil) 72 | full_filename(thumbnail).gsub %r(^#{Regexp.escape(base_path)}), '' 73 | end 74 | 75 | def filename=(value) 76 | @old_filename = full_filename unless filename.nil? || @old_filename 77 | write_attribute :filename, sanitize_filename(value) 78 | end 79 | 80 | # Creates a temp file from the currently saved file. 81 | def create_temp_file 82 | copy_to_temp_file full_filename 83 | end 84 | 85 | protected 86 | # Destroys the file. Called in the after_destroy callback 87 | def destroy_file 88 | FileUtils.rm full_filename 89 | # remove directory also if it is now empty 90 | Dir.rmdir(File.dirname(full_filename)) if (Dir.entries(File.dirname(full_filename))-['.','..']).empty? 91 | rescue 92 | logger.info "Exception destroying #{full_filename.inspect}: [#{$!.class.name}] #{$1.to_s}" 93 | logger.warn $!.backtrace.collect { |b| " > #{b}" }.join("\n") 94 | end 95 | 96 | # Renames the given file before saving 97 | def rename_file 98 | return unless @old_filename && @old_filename != full_filename 99 | if save_attachment? && File.exists?(@old_filename) 100 | FileUtils.rm @old_filename 101 | elsif File.exists?(@old_filename) 102 | FileUtils.mv @old_filename, full_filename 103 | end 104 | @old_filename = nil 105 | true 106 | end 107 | 108 | # Saves the file to the file system 109 | def save_to_storage 110 | if save_attachment? 111 | # TODO: This overwrites the file if it exists, maybe have an allow_overwrite option? 112 | FileUtils.mkdir_p(File.dirname(full_filename)) 113 | FileUtils.cp(temp_path, full_filename) 114 | FileUtils.chmod(attachment_options[:chmod] || 0644, full_filename) 115 | end 116 | @old_filename = nil 117 | true 118 | end 119 | 120 | def current_data 121 | File.file?(full_filename) ? File.read(full_filename) : nil 122 | end 123 | end 124 | end 125 | end 126 | end 127 | -------------------------------------------------------------------------------- /test/backends/file_system_test.rb: -------------------------------------------------------------------------------- 1 | require File.expand_path(File.join(File.dirname(__FILE__), '..', 'test_helper')) 2 | require 'digest/sha2' 3 | 4 | class FileSystemTest < Test::Unit::TestCase 5 | include BaseAttachmentTests 6 | attachment_model FileAttachment 7 | 8 | def test_filesystem_size_for_file_attachment(klass = FileAttachment) 9 | attachment_model klass 10 | assert_created 1 do 11 | attachment = upload_file :filename => '/files/rails.png' 12 | assert_equal attachment.size, File.open(attachment.full_filename).stat.size 13 | end 14 | end 15 | 16 | test_against_subclass :test_filesystem_size_for_file_attachment, FileAttachment 17 | 18 | def test_should_not_overwrite_file_attachment(klass = FileAttachment) 19 | attachment_model klass 20 | assert_created 2 do 21 | real = upload_file :filename => '/files/rails.png' 22 | assert_valid real 23 | assert !real.new_record?, real.errors.full_messages.join("\n") 24 | assert !real.size.zero? 25 | 26 | fake = upload_file :filename => '/files/fake/rails.png' 27 | assert_valid fake 28 | assert !fake.size.zero? 29 | 30 | assert_not_equal File.open(real.full_filename).stat.size, File.open(fake.full_filename).stat.size 31 | end 32 | end 33 | 34 | test_against_subclass :test_should_not_overwrite_file_attachment, FileAttachment 35 | 36 | def test_should_store_file_attachment_in_filesystem(klass = FileAttachment) 37 | attachment_model klass 38 | attachment = nil 39 | assert_created do 40 | attachment = upload_file :filename => '/files/rails.png' 41 | assert_valid attachment 42 | assert File.exists?(attachment.full_filename), "#{attachment.full_filename} does not exist" 43 | end 44 | attachment 45 | end 46 | 47 | test_against_subclass :test_should_store_file_attachment_in_filesystem, FileAttachment 48 | 49 | def test_should_delete_old_file_when_updating(klass = FileAttachment) 50 | attachment_model klass 51 | attachment = upload_file :filename => '/files/rails.png' 52 | old_filename = attachment.full_filename 53 | assert_not_created do 54 | use_temp_file 'files/rails.png' do |file| 55 | attachment.filename = 'rails2.png' 56 | attachment.temp_paths.unshift File.join(fixture_path, file) 57 | attachment.save! 58 | assert File.exists?(attachment.full_filename), "#{attachment.full_filename} does not exist" 59 | assert !File.exists?(old_filename), "#{old_filename} still exists" 60 | end 61 | end 62 | end 63 | 64 | test_against_subclass :test_should_delete_old_file_when_updating, FileAttachment 65 | 66 | def test_should_delete_old_file_when_renaming(klass = FileAttachment) 67 | attachment_model klass 68 | attachment = upload_file :filename => '/files/rails.png' 69 | old_filename = attachment.full_filename 70 | assert_not_created do 71 | attachment.filename = 'rails2.png' 72 | attachment.save 73 | assert File.exists?(attachment.full_filename), "#{attachment.full_filename} does not exist" 74 | assert !File.exists?(old_filename), "#{old_filename} still exists" 75 | assert !attachment.reload.size.zero? 76 | assert_equal 'rails2.png', attachment.filename 77 | end 78 | end 79 | 80 | test_against_subclass :test_should_delete_old_file_when_renaming, FileAttachment 81 | 82 | def test_path_partitioning_works_on_integer_id(klass = FileAttachment) 83 | attachment_model klass 84 | 85 | # Create a random attachment object, doesn't matter what. 86 | attachment = upload_file :filename => '/files/rails.png' 87 | old_id = attachment.id 88 | attachment.id = 1 89 | 90 | begin 91 | assert_equal ["0000", "0001", "bar.txt"], attachment.send(:partitioned_path, "bar.txt") 92 | ensure 93 | attachment.id = old_id 94 | end 95 | end 96 | 97 | test_against_subclass :test_path_partitioning_works_on_integer_id, FileAttachment 98 | 99 | def test_path_partitioning_with_string_id_works_by_generating_hash(klass = FileAttachmentWithStringId) 100 | attachment_model klass 101 | 102 | # Create a random attachment object, doesn't matter what. 103 | attachment = upload_file :filename => '/files/rails.png' 104 | old_id = attachment.id 105 | attachment.id = "hello world some long string" 106 | hash = Digest::SHA512.hexdigest("hello world some long string") 107 | 108 | begin 109 | assert_equal [ 110 | hash[0..31], 111 | hash[32..63], 112 | hash[64..95], 113 | hash[96..127], 114 | "bar.txt" 115 | ], attachment.send(:partitioned_path, "bar.txt") 116 | ensure 117 | attachment.id = old_id 118 | end 119 | end 120 | 121 | test_against_subclass :test_path_partitioning_with_string_id_works_by_generating_hash, FileAttachmentWithStringId 122 | 123 | def test_path_partition_string_id_hashing_is_turned_off_if_id_is_uuid(klass = FileAttachmentWithUuid) 124 | attachment_model klass 125 | 126 | # Create a random attachment object, doesn't matter what. 127 | attachment = upload_file :filename => '/files/rails.png' 128 | old_id = attachment.id 129 | attachment.id = "0c0743b698483569dc65909a8cdb3bf9" 130 | 131 | begin 132 | assert_equal [ 133 | "0c0743b698483569", 134 | "dc65909a8cdb3bf9", 135 | "bar.txt" 136 | ], attachment.send(:partitioned_path, "bar.txt") 137 | ensure 138 | attachment.id = old_id 139 | end 140 | end 141 | 142 | test_against_subclass :test_path_partition_string_id_hashing_is_turned_off_if_id_is_uuid, FileAttachmentWithUuid 143 | end 144 | -------------------------------------------------------------------------------- /lib/technoweenie/attachment_fu/processors/mini_magick_processor.rb: -------------------------------------------------------------------------------- 1 | require 'mini_magick' 2 | module Technoweenie # :nodoc: 3 | module AttachmentFu # :nodoc: 4 | module Processors 5 | module MiniMagickProcessor 6 | def self.included(base) 7 | base.send :extend, ClassMethods 8 | base.alias_method_chain :process_attachment, :processing 9 | end 10 | 11 | module ClassMethods 12 | # Yields a block containing an MiniMagick Image for the given binary data. 13 | def with_image(file, &block) 14 | begin 15 | binary_data = file.is_a?(MiniMagick::Image) ? file : MiniMagick::Image.from_file(file) unless !Object.const_defined?(:MiniMagick) 16 | rescue 17 | # Log the failure to load the image. 18 | logger.debug("Exception working with image: #{$!}") 19 | binary_data = nil 20 | end 21 | block.call binary_data if block && binary_data 22 | ensure 23 | !binary_data.nil? 24 | end 25 | end 26 | 27 | protected 28 | def process_attachment_with_processing 29 | return unless process_attachment_without_processing 30 | with_image do |img| 31 | resize_image_or_thumbnail! img 32 | self.width = img[:width] if respond_to?(:width) 33 | self.height = img[:height] if respond_to?(:height) 34 | callback_with_args :after_resize, img 35 | end if image? 36 | end 37 | 38 | # Performs the actual resizing operation for a thumbnail 39 | def resize_image(img, size) 40 | size = size.first if size.is_a?(Array) && size.length == 1 41 | img.combine_options do |commands| 42 | commands.strip unless attachment_options[:keep_profile] 43 | 44 | # gif are not handled correct, this is a hack, but it seems to work. 45 | if img.output =~ / GIF / 46 | img.format("png") 47 | end 48 | 49 | if size.is_a?(Fixnum) || (size.is_a?(Array) && size.first.is_a?(Fixnum)) 50 | if size.is_a?(Fixnum) 51 | size = [size, size] 52 | commands.resize(size.join('x')) 53 | else 54 | commands.resize(size.join('x') + '!') 55 | end 56 | # extend to thumbnail size 57 | elsif size.is_a?(String) and size =~ /e$/ 58 | size = size.gsub(/e/, '') 59 | commands.resize(size.to_s + '>') 60 | commands.background('#ffffff') 61 | commands.gravity('center') 62 | commands.extent(size) 63 | # crop thumbnail, the smart way 64 | elsif size.is_a?(String) and size =~ /c$/ 65 | size = size.gsub(/c/, '') 66 | 67 | # calculate sizes and aspect ratio 68 | thumb_width, thumb_height = size.split("x") 69 | thumb_width = thumb_width.to_f 70 | thumb_height = thumb_height.to_f 71 | 72 | thumb_aspect = thumb_width.to_f / thumb_height.to_f 73 | image_width, image_height = img[:width].to_f, img[:height].to_f 74 | image_aspect = image_width / image_height 75 | 76 | # only crop if image is not smaller in both dimensions 77 | unless image_width < thumb_width and image_height < thumb_height 78 | command = calculate_offset(image_width,image_height,image_aspect,thumb_width,thumb_height,thumb_aspect) 79 | 80 | # crop image 81 | commands.extract(command) 82 | end 83 | 84 | # don not resize if image is not as height or width then thumbnail 85 | if image_width < thumb_width or image_height < thumb_height 86 | commands.background('#ffffff') 87 | commands.gravity('center') 88 | commands.extent(size) 89 | # resize image 90 | else 91 | commands.resize("#{size.to_s}") 92 | end 93 | # crop end 94 | else 95 | commands.resize(size.to_s) 96 | end 97 | end 98 | temp_paths.unshift img 99 | end 100 | 101 | def calculate_offset(image_width,image_height,image_aspect,thumb_width,thumb_height,thumb_aspect) 102 | # only crop if image is not smaller in both dimensions 103 | 104 | # special cases, image smaller in one dimension then thumbsize 105 | if image_width < thumb_width 106 | offset = (image_height / 2) - (thumb_height / 2) 107 | command = "#{image_width}x#{thumb_height}+0+#{offset}" 108 | elsif image_height < thumb_height 109 | offset = (image_width / 2) - (thumb_width / 2) 110 | command = "#{thumb_width}x#{image_height}+#{offset}+0" 111 | 112 | # normal thumbnail generation 113 | # calculate height and offset y, width is fixed 114 | elsif (image_aspect <= thumb_aspect or image_width < thumb_width) and image_height > thumb_height 115 | height = image_width / thumb_aspect 116 | offset = (image_height / 2) - (height / 2) 117 | command = "#{image_width}x#{height}+0+#{offset}" 118 | # calculate width and offset x, height is fixed 119 | else 120 | width = image_height * thumb_aspect 121 | offset = (image_width / 2) - (width / 2) 122 | command = "#{width}x#{image_height}+#{offset}+0" 123 | end 124 | # crop image 125 | command 126 | end 127 | 128 | 129 | end 130 | end 131 | end 132 | end -------------------------------------------------------------------------------- /test/fixtures/attachment.rb: -------------------------------------------------------------------------------- 1 | class Attachment < ActiveRecord::Base 2 | @@saves = 0 3 | cattr_accessor :saves 4 | has_attachment :processor => :rmagick 5 | validates_as_attachment 6 | after_attachment_saved do |record| 7 | self.saves += 1 8 | end 9 | end 10 | 11 | class SmallAttachment < Attachment 12 | has_attachment :max_size => 1.kilobyte 13 | end 14 | 15 | class BigAttachment < Attachment 16 | has_attachment :size => 1.megabyte..2.megabytes 17 | end 18 | 19 | class PdfAttachment < Attachment 20 | has_attachment :content_type => 'pdf' 21 | end 22 | 23 | class DocAttachment < Attachment 24 | has_attachment :content_type => %w(pdf doc txt) 25 | end 26 | 27 | class ImageAttachment < Attachment 28 | has_attachment :content_type => :image, :resize_to => [50,50] 29 | end 30 | 31 | class ImageOrPdfAttachment < Attachment 32 | has_attachment :content_type => ['pdf', :image], :resize_to => 'x50' 33 | end 34 | 35 | class ImageWithThumbsAttachment < Attachment 36 | has_attachment :thumbnails => { :thumb => [50, 50], :geometry => 'x50' }, :resize_to => [55,55] 37 | after_resize do |record, img| 38 | # record.aspect_ratio = img.columns.to_f / img.rows.to_f 39 | end 40 | end 41 | 42 | class FileAttachment < ActiveRecord::Base 43 | has_attachment :path_prefix => 'vendor/plugins/attachment_fu/test/files', :processor => :rmagick 44 | validates_as_attachment 45 | end 46 | 47 | class FileAttachmentWithStringId < ActiveRecord::Base 48 | set_table_name 'file_attachments_with_string_id' 49 | has_attachment :path_prefix => 'vendor/plugins/attachment_fu/test/files', :processor => :rmagick 50 | validates_as_attachment 51 | 52 | before_validation :auto_generate_id 53 | before_save :auto_generate_id 54 | @@last_id = 0 55 | 56 | private 57 | def auto_generate_id 58 | @@last_id += 1 59 | self.id = "id_#{@@last_id}" 60 | end 61 | end 62 | 63 | class FileAttachmentWithUuid < ActiveRecord::Base 64 | set_table_name 'file_attachments_with_string_id' 65 | has_attachment :path_prefix => 'vendor/plugins/attachment_fu/test/files', :processor => :rmagick, :uuid_primary_key => true 66 | validates_as_attachment 67 | 68 | before_validation :auto_generate_id 69 | before_save :auto_generate_id 70 | @@last_id = 0 71 | 72 | private 73 | def auto_generate_id 74 | @@last_id += 1 75 | self.id = "%0127dx" % @@last_id 76 | end 77 | end 78 | 79 | class ImageFileAttachment < FileAttachment 80 | has_attachment :path_prefix => 'vendor/plugins/attachment_fu/test/files', 81 | :content_type => :image, :resize_to => [50,50] 82 | end 83 | 84 | class ImageWithThumbsFileAttachment < FileAttachment 85 | has_attachment :path_prefix => 'vendor/plugins/attachment_fu/test/files', 86 | :thumbnails => { :thumb => [50, 50], :geometry => 'x50' }, :resize_to => [55,55] 87 | after_resize do |record, img| 88 | # record.aspect_ratio = img.columns.to_f / img.rows.to_f 89 | end 90 | end 91 | 92 | class ImageWithThumbsClassFileAttachment < FileAttachment 93 | # use file_system_path to test backwards compatibility 94 | has_attachment :file_system_path => 'vendor/plugins/attachment_fu/test/files', 95 | :thumbnails => { :thumb => [50, 50] }, :resize_to => [55,55], 96 | :thumbnail_class => 'ImageThumbnail' 97 | end 98 | 99 | class ImageThumbnail < FileAttachment 100 | has_attachment :path_prefix => 'vendor/plugins/attachment_fu/test/files/thumbnails' 101 | end 102 | 103 | # no parent 104 | class OrphanAttachment < ActiveRecord::Base 105 | has_attachment :processor => :rmagick 106 | validates_as_attachment 107 | end 108 | 109 | # no filename, no size, no content_type 110 | class MinimalAttachment < ActiveRecord::Base 111 | has_attachment :path_prefix => 'vendor/plugins/attachment_fu/test/files', :processor => :rmagick 112 | validates_as_attachment 113 | 114 | def filename 115 | "#{id}.file" 116 | end 117 | end 118 | 119 | begin 120 | class ImageScienceAttachment < ActiveRecord::Base 121 | has_attachment :path_prefix => 'vendor/plugins/attachment_fu/test/files', 122 | :processor => :image_science, :thumbnails => { :thumb => [50, 51], :geometry => '31>' }, :resize_to => 55 123 | end 124 | rescue MissingSourceFile 125 | puts $!.message 126 | puts "no ImageScience" 127 | end 128 | 129 | begin 130 | class CoreImageAttachment < ActiveRecord::Base 131 | has_attachment :path_prefix => 'vendor/plugins/attachment_fu/test/files', 132 | :processor => :core_image, :thumbnails => { :thumb => [50, 51], :geometry => '31>' }, :resize_to => 55 133 | end 134 | rescue MissingSourceFile 135 | puts $!.message 136 | puts "no CoreImage" 137 | end 138 | 139 | begin 140 | class MiniMagickAttachment < ActiveRecord::Base 141 | has_attachment :path_prefix => 'vendor/plugins/attachment_fu/test/files', 142 | :processor => :mini_magick, :thumbnails => { :thumb => [50, 51], :geometry => '31>' }, :resize_to => 55 143 | end 144 | rescue MissingSourceFile 145 | puts $!.message 146 | puts "no Mini Magick" 147 | end 148 | 149 | begin 150 | class GD2Attachment < ActiveRecord::Base 151 | has_attachment :path_prefix => 'vendor/plugins/attachment_fu/test/files', 152 | :processor => :gd2, :thumbnails => { :thumb => [50, 51], :geometry => '31>' }, :resize_to => 55 153 | end 154 | rescue MissingSourceFile 155 | puts $!.message 156 | puts "no GD2" 157 | end 158 | 159 | 160 | begin 161 | class MiniMagickAttachment < ActiveRecord::Base 162 | has_attachment :path_prefix => 'vendor/plugins/attachment_fu/test/files', 163 | :processor => :mini_magick, :thumbnails => { :thumb => [50, 51], :geometry => '31>' }, :resize_to => 55 164 | end 165 | class ImageThumbnailCrop < MiniMagickAttachment 166 | has_attachment :path_prefix => 'vendor/plugins/attachment_fu/test/files', 167 | :thumbnails => { :square => "50x50c", :vertical => "30x60c", :horizontal => "60x30c"} 168 | 169 | # TODO this is a bad duplication, this method is in the MiniMagick Processor 170 | def self.calculate_offset(image_width,image_height,image_aspect,thumb_width,thumb_height,thumb_aspect) 171 | # only crop if image is not smaller in both dimensions 172 | 173 | # special cases, image smaller in one dimension then thumbsize 174 | if image_width < thumb_width 175 | offset = (image_height / 2) - (thumb_height / 2) 176 | command = "#{image_width}x#{thumb_height}+0+#{offset}" 177 | elsif image_height < thumb_height 178 | offset = (image_width / 2) - (thumb_width / 2) 179 | command = "#{thumb_width}x#{image_height}+#{offset}+0" 180 | 181 | # normal thumbnail generation 182 | # calculate height and offset y, width is fixed 183 | elsif (image_aspect <= thumb_aspect or image_width < thumb_width) and image_height > thumb_height 184 | height = image_width / thumb_aspect 185 | offset = (image_height / 2) - (height / 2) 186 | command = "#{image_width}x#{height}+0+#{offset}" 187 | # calculate width and offset x, height is fixed 188 | else 189 | width = image_height * thumb_aspect 190 | offset = (image_width / 2) - (width / 2) 191 | command = "#{width}x#{image_height}+#{offset}+0" 192 | end 193 | # crop image 194 | command 195 | end 196 | end 197 | 198 | rescue MissingSourceFile 199 | end 200 | 201 | 202 | 203 | begin 204 | class S3Attachment < ActiveRecord::Base 205 | has_attachment :storage => :s3, :processor => :rmagick, :s3_config_path => File.join(File.dirname(__FILE__), '../amazon_s3.yml') 206 | validates_as_attachment 207 | end 208 | 209 | class S3WithPathPrefixAttachment < S3Attachment 210 | has_attachment :storage => :s3, :path_prefix => 'some/custom/path/prefix', :processor => :rmagick 211 | validates_as_attachment 212 | end 213 | rescue 214 | puts "S3 error: #{$!}" 215 | end 216 | -------------------------------------------------------------------------------- /README: -------------------------------------------------------------------------------- 1 | attachment-fu 2 | ============= 3 | 4 | attachment_fu is a plugin by Rick Olson (aka technoweenie ) and is the successor to acts_as_attachment. To get a basic run-through of its capabilities, check out Mike Clark's tutorial . 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 three storage options for files uploaded through attachment_fu: 13 | File system 14 | Database file 15 | Amazon S3 16 | 17 | 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. 18 | 19 | 20 | attachment_fu models 21 | ==================== 22 | 23 | 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). 24 | 25 | In the model there are two methods made available by this plugins: has_attachment and validates_as_attachment. 26 | 27 | has_attachment(options = {}) 28 | This method accepts the options in a hash: 29 | :content_type # Allowed content types. 30 | # Allows all by default. Use :image to allow all standard image types. 31 | :min_size # Minimum size allowed. 32 | # 1 byte is the default. 33 | :max_size # Maximum size allowed. 34 | # 1.megabyte is the default. 35 | :size # Range of sizes allowed. 36 | # (1..1.megabyte) is the default. This overrides the :min_size and :max_size options. 37 | :resize_to # Used by RMagick to resize images. 38 | # Pass either an array of width/height, or a geometry string. 39 | :thumbnails # Specifies a set of thumbnails to generate. 40 | # This accepts a hash of filename suffixes and RMagick resizing options. 41 | # This option need only be included if you want thumbnailing. 42 | :thumbnail_class # Set which model class to use for thumbnails. 43 | # This current attachment class is used by default. 44 | :path_prefix # Path to store the uploaded files in. 45 | # Uses public/#{table_name} by default for the filesystem, and just #{table_name} for the S3 backend. 46 | # Setting this sets the :storage to :file_system. 47 | :partition # Whether to partiton files in directories like /0000/0001/image.jpg. Default is true. Only applicable to the :file_system backend. 48 | :storage # Specifies the storage system to use.. 49 | # Defaults to :db_file. Options are :file_system, :db_file, and :s3. 50 | :processor # Sets the image processor to use for resizing of the attached image. 51 | # Options include ImageScience, Rmagick, and MiniMagick. Default is whatever is installed. 52 | :uuid_primary_key # If your model's primary key is a 128-bit UUID in hexadecimal format, then set this to true. 53 | :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. 54 | 55 | 56 | Examples: 57 | has_attachment :max_size => 1.kilobyte 58 | has_attachment :size => 1.megabyte..2.megabytes 59 | has_attachment :content_type => 'application/pdf' 60 | has_attachment :content_type => ['application/pdf', 'application/msword', 'text/plain'] 61 | has_attachment :content_type => :image, :resize_to => [50,50] 62 | has_attachment :content_type => ['application/pdf', :image], :resize_to => 'x50' 63 | has_attachment :thumbnails => { :thumb => [50, 50], :geometry => 'x50' } 64 | has_attachment :storage => :file_system, :path_prefix => 'public/files' 65 | has_attachment :storage => :file_system, :path_prefix => 'public/files', 66 | :content_type => :image, :resize_to => [50,50], :partition => false 67 | has_attachment :storage => :file_system, :path_prefix => 'public/files', 68 | :thumbnails => { :thumb => [50, 50], :geometry => 'x50' } 69 | has_attachment :storage => :s3 70 | 71 | validates_as_attachment 72 | 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. 73 | 74 | Example: 75 | validates_as_attachment 76 | 77 | 78 | attachment_fu migrations 79 | ======================== 80 | 81 | Fields for attachment_fu metadata tables... 82 | in general: 83 | size, :integer # file size in bytes 84 | content_type, :string # mime type, ex: application/mp3 85 | filename, :string # sanitized filename 86 | that reference images: 87 | height, :integer # in pixels 88 | width, :integer # in pixels 89 | that reference images that will be thumbnailed: 90 | parent_id, :integer # id of parent image (on the same table, a self-referencing foreign-key). 91 | # Only populated if the current object is a thumbnail. 92 | thumbnail, :string # the 'type' of thumbnail this attachment record describes. 93 | # Only populated if the current object is a thumbnail. 94 | # Usage: 95 | # [ In Model 'Avatar' ] 96 | # has_attachment :content_type => :image, 97 | # :storage => :file_system, 98 | # :max_size => 500.kilobytes, 99 | # :resize_to => '320x200>', 100 | # :thumbnails => { :small => '10x10>', 101 | # :thumb => '100x100>' } 102 | # [ Elsewhere ] 103 | # @user.avatar.thumbnails.first.thumbnail #=> 'small' 104 | that reference files stored in the database (:db_file): 105 | db_file_id, :integer # id of the file in the database (foreign key) 106 | 107 | Field for attachment_fu db_files table: 108 | data, :binary # binary file data, for use in database file storage 109 | 110 | 111 | attachment_fu views 112 | =================== 113 | 114 | There are two main views tasks that will be directly affected by attachment_fu: upload forms and displaying uploaded images. 115 | 116 | There are two parts of the upload form that differ from typical usage. 117 | 1. Include ':multipart => true' in the html options of the form_for tag. 118 | Example: 119 | <% form_for(:attachment_metadata, :url => { :action => "create" }, :html => { :multipart => true }) do |form| %> 120 | 121 | 2. Use the file_field helper with :uploaded_data as the field name. 122 | Example: 123 | <%= form.file_field :uploaded_data %> 124 | 125 | Displaying uploaded images is made easy by the public_filename method of the ActiveRecord attachment objects using file system and s3 storage. 126 | 127 | public_filename(thumbnail = nil) 128 | Returns the public path to the file. If a thumbnail prefix is specified it will return the public file path to the corresponding thumbnail. 129 | Examples: 130 | attachment_obj.public_filename #=> /attachments/2/file.jpg 131 | attachment_obj.public_filename(:thumb) #=> /attachments/2/file_thumb.jpg 132 | attachment_obj.public_filename(:small) #=> /attachments/2/file_small.jpg 133 | 134 | When serving files from database storage, doing more than simply downloading the file is beyond the scope of this document. 135 | 136 | 137 | attachment_fu controllers 138 | ========================= 139 | 140 | There are two considerations to take into account when using attachment_fu in controllers. 141 | 142 | The first is when the files have no publicly accessible path and need to be downloaded through an action. 143 | 144 | Example: 145 | def readme 146 | send_file '/path/to/readme.txt', :type => 'plain/text', :disposition => 'inline' 147 | end 148 | 149 | See the possible values for send_file for reference. 150 | 151 | 152 | The second is when saving the file when submitted from a form. 153 | Example in view: 154 | <%= form.file_field :attachable, :uploaded_data %> 155 | 156 | Example in controller: 157 | def create 158 | @attachable_file = AttachmentMetadataModel.new(params[:attachable]) 159 | if @attachable_file.save 160 | flash[:notice] = 'Attachment was successfully created.' 161 | redirect_to attachable_url(@attachable_file) 162 | else 163 | render :action => :new 164 | end 165 | end 166 | 167 | attachement_fu scripting 168 | ==================================== 169 | 170 | You may wish to import a large number of images or attachments. 171 | The following example shows how to upload a file from a script. 172 | 173 | #!/usr/bin/env ./script/runner 174 | 175 | # required to use ActionController::TestUploadedFile 176 | require 'action_controller' 177 | require 'action_controller/test_process.rb' 178 | 179 | path = "./public/images/x.jpg" 180 | 181 | # mimetype is a string like "image/jpeg". One way to get the mimetype for a given file on a UNIX system 182 | # mimetype = `file -ib #{path}`.gsub(/\n/,"") 183 | 184 | mimetype = "image/jpeg" 185 | 186 | # This will "upload" the file at path and create the new model. 187 | @attachable = AttachmentMetadataModel.new(:uploaded_data => ActionController::TestUploadedFile.new(path, mimetype)) 188 | @attachable.save 189 | -------------------------------------------------------------------------------- /test/processors/rmagick_test.rb: -------------------------------------------------------------------------------- 1 | require File.expand_path(File.join(File.dirname(__FILE__), '..', 'test_helper')) 2 | 3 | class RmagickTest < Test::Unit::TestCase 4 | attachment_model Attachment 5 | 6 | if Object.const_defined?(:Magick) 7 | def test_should_create_image_from_uploaded_file 8 | assert_created do 9 | attachment = upload_file :filename => '/files/rails.png' 10 | assert_valid attachment 11 | assert !attachment.db_file.new_record? if attachment.respond_to?(:db_file) 12 | assert attachment.image? 13 | assert !attachment.size.zero? 14 | #assert_equal 1784, attachment.size 15 | assert_equal 50, attachment.width 16 | assert_equal 64, attachment.height 17 | assert_equal '50x64', attachment.image_size 18 | end 19 | end 20 | 21 | def test_should_create_image_from_uploaded_file_with_custom_content_type 22 | assert_created do 23 | attachment = upload_file :content_type => 'foo/bar', :filename => '/files/rails.png' 24 | assert_valid attachment 25 | assert !attachment.image? 26 | assert !attachment.db_file.new_record? if attachment.respond_to?(:db_file) 27 | assert !attachment.size.zero? 28 | #assert_equal 1784, attachment.size 29 | assert_nil attachment.width 30 | assert_nil attachment.height 31 | assert_equal [], attachment.thumbnails 32 | end 33 | end 34 | 35 | def test_should_create_thumbnail 36 | attachment = upload_file :filename => '/files/rails.png' 37 | 38 | assert_created do 39 | basename, ext = attachment.filename.split '.' 40 | thumbnail = attachment.create_or_update_thumbnail(attachment.create_temp_file, 'thumb', 50, 50) 41 | assert_valid thumbnail 42 | assert !thumbnail.size.zero? 43 | #assert_in_delta 4673, thumbnail.size, 2 44 | assert_equal 50, thumbnail.width 45 | assert_equal 50, thumbnail.height 46 | assert_equal [thumbnail.id], attachment.thumbnails.collect(&:id) 47 | assert_equal attachment.id, thumbnail.parent_id if thumbnail.respond_to?(:parent_id) 48 | assert_equal "#{basename}_thumb.#{ext}", thumbnail.filename 49 | end 50 | end 51 | 52 | def test_should_create_thumbnail_with_geometry_string 53 | attachment = upload_file :filename => '/files/rails.png' 54 | 55 | assert_created do 56 | basename, ext = attachment.filename.split '.' 57 | thumbnail = attachment.create_or_update_thumbnail(attachment.create_temp_file, 'thumb', 'x50') 58 | assert_valid thumbnail 59 | assert !thumbnail.size.zero? 60 | #assert_equal 3915, thumbnail.size 61 | assert_equal 39, thumbnail.width 62 | assert_equal 50, thumbnail.height 63 | assert_equal [thumbnail], attachment.thumbnails 64 | assert_equal attachment.id, thumbnail.parent_id if thumbnail.respond_to?(:parent_id) 65 | assert_equal "#{basename}_thumb.#{ext}", thumbnail.filename 66 | end 67 | end 68 | 69 | def test_should_resize_image(klass = ImageAttachment) 70 | attachment_model klass 71 | assert_equal [50, 50], attachment_model.attachment_options[:resize_to] 72 | attachment = upload_file :filename => '/files/rails.png' 73 | assert_valid attachment 74 | assert !attachment.db_file.new_record? if attachment.respond_to?(:db_file) 75 | assert attachment.image? 76 | assert !attachment.size.zero? 77 | #assert_in_delta 4673, attachment.size, 2 78 | assert_equal 50, attachment.width 79 | assert_equal 50, attachment.height 80 | end 81 | 82 | test_against_subclass :test_should_resize_image, ImageAttachment 83 | 84 | def test_should_resize_image_with_geometry(klass = ImageOrPdfAttachment) 85 | attachment_model klass 86 | assert_equal 'x50', attachment_model.attachment_options[:resize_to] 87 | attachment = upload_file :filename => '/files/rails.png' 88 | assert_valid attachment 89 | assert !attachment.db_file.new_record? if attachment.respond_to?(:db_file) 90 | assert attachment.image? 91 | assert !attachment.size.zero? 92 | #assert_equal 3915, attachment.size 93 | assert_equal 39, attachment.width 94 | assert_equal 50, attachment.height 95 | end 96 | 97 | test_against_subclass :test_should_resize_image_with_geometry, ImageOrPdfAttachment 98 | 99 | def test_should_give_correct_thumbnail_filenames(klass = ImageWithThumbsFileAttachment) 100 | attachment_model klass 101 | assert_created 3 do 102 | attachment = upload_file :filename => '/files/rails.png' 103 | thumb = attachment.thumbnails.detect { |t| t.filename =~ /_thumb/ } 104 | geo = attachment.thumbnails.detect { |t| t.filename =~ /_geometry/ } 105 | 106 | [attachment, thumb, geo].each { |record| assert_valid record } 107 | 108 | assert_match /rails\.png$/, attachment.full_filename 109 | assert_match /rails_geometry\.png$/, attachment.full_filename(:geometry) 110 | assert_match /rails_thumb\.png$/, attachment.full_filename(:thumb) 111 | end 112 | end 113 | 114 | test_against_subclass :test_should_give_correct_thumbnail_filenames, ImageWithThumbsFileAttachment 115 | 116 | def test_should_automatically_create_thumbnails(klass = ImageWithThumbsAttachment) 117 | attachment_model klass 118 | assert_created 3 do 119 | attachment = upload_file :filename => '/files/rails.png' 120 | assert_valid attachment 121 | assert !attachment.size.zero? 122 | #assert_equal 1784, attachment.size 123 | assert_equal 55, attachment.width 124 | assert_equal 55, attachment.height 125 | assert_equal 2, attachment.thumbnails.length 126 | 127 | thumb = attachment.thumbnails.detect { |t| t.filename =~ /_thumb/ } 128 | assert !thumb.new_record?, thumb.errors.full_messages.join("\n") 129 | assert !thumb.size.zero? 130 | #assert_in_delta 4673, thumb.size, 2 131 | assert_equal 50, thumb.width 132 | assert_equal 50, thumb.height 133 | 134 | geo = attachment.thumbnails.detect { |t| t.filename =~ /_geometry/ } 135 | assert !geo.new_record?, geo.errors.full_messages.join("\n") 136 | assert !geo.size.zero? 137 | #assert_equal 3915, geo.size 138 | assert_equal 50, geo.width 139 | assert_equal 50, geo.height 140 | end 141 | end 142 | 143 | test_against_subclass :test_should_automatically_create_thumbnails, ImageWithThumbsAttachment 144 | 145 | # same as above method, but test it on a file model 146 | test_against_class :test_should_automatically_create_thumbnails, ImageWithThumbsFileAttachment 147 | test_against_subclass :test_should_automatically_create_thumbnails_on_class, ImageWithThumbsFileAttachment 148 | 149 | def test_should_use_thumbnail_subclass(klass = ImageWithThumbsClassFileAttachment) 150 | attachment_model klass 151 | attachment = nil 152 | assert_difference ImageThumbnail, :count do 153 | attachment = upload_file :filename => '/files/rails.png' 154 | assert_valid attachment 155 | end 156 | assert_kind_of ImageThumbnail, attachment.thumbnails.first 157 | if attachment.thumbnails.first.respond_to?(:parent) 158 | assert_equal attachment.id, attachment.thumbnails.first.parent.id 159 | assert_kind_of FileAttachment, attachment.thumbnails.first.parent 160 | end 161 | assert_equal 'rails_thumb.png', attachment.thumbnails.first.filename 162 | assert_equal attachment.thumbnails.first.full_filename, attachment.full_filename(attachment.thumbnails.first.thumbnail), 163 | "#full_filename does not use thumbnail class' path." 164 | assert_equal attachment.destroy, attachment 165 | end 166 | 167 | test_against_subclass :test_should_use_thumbnail_subclass, ImageWithThumbsClassFileAttachment 168 | 169 | def test_should_remove_old_thumbnail_files_when_updating(klass = ImageWithThumbsFileAttachment) 170 | attachment_model klass 171 | attachment = nil 172 | assert_created 3 do 173 | attachment = upload_file :filename => '/files/rails.png' 174 | end 175 | 176 | old_filenames = [attachment.full_filename] + attachment.thumbnails.collect(&:full_filename) 177 | 178 | assert_not_created do 179 | use_temp_file "files/rails.png" do |file| 180 | attachment.filename = 'rails2.png' 181 | attachment.temp_paths.unshift File.join(fixture_path, file) 182 | attachment.save 183 | new_filenames = [attachment.reload.full_filename] + attachment.thumbnails.collect { |t| t.reload.full_filename } 184 | new_filenames.each { |f| assert File.exists?(f), "#{f} does not exist" } 185 | old_filenames.each { |f| assert !File.exists?(f), "#{f} still exists" } 186 | end 187 | end 188 | end 189 | 190 | test_against_subclass :test_should_remove_old_thumbnail_files_when_updating, ImageWithThumbsFileAttachment 191 | 192 | def test_should_delete_file_when_in_file_system_when_attachment_record_destroyed(klass = ImageWithThumbsFileAttachment) 193 | attachment_model klass 194 | attachment = upload_file :filename => '/files/rails.png' 195 | filenames = [attachment.full_filename] + attachment.thumbnails.collect(&:full_filename) 196 | filenames.each { |f| assert File.exists?(f), "#{f} never existed to delete on destroy" } 197 | attachment.destroy 198 | filenames.each { |f| assert !File.exists?(f), "#{f} still exists" } 199 | end 200 | 201 | test_against_subclass :test_should_delete_file_when_in_file_system_when_attachment_record_destroyed, ImageWithThumbsFileAttachment 202 | 203 | def test_should_have_full_filename_method(klass = FileAttachment) 204 | attachment_model klass 205 | attachment = upload_file :filename => '/files/rails.png' 206 | assert_respond_to attachment, :full_filename 207 | end 208 | 209 | test_against_subclass :test_should_have_full_filename_method, FileAttachment 210 | 211 | def test_should_overwrite_old_thumbnail_records_when_updating(klass = ImageWithThumbsAttachment) 212 | attachment_model klass 213 | attachment = nil 214 | assert_created 3 do 215 | attachment = upload_file :filename => '/files/rails.png' 216 | end 217 | assert_not_created do # no new db_file records 218 | use_temp_file "files/rails.png" do |file| 219 | attachment.filename = 'rails2.png' 220 | # The above test (#test_should_have_full_filename_method) to pass before be can set the temp_path below -- 221 | # #temp_path calls #full_filename, which is not getting mixed into the attachment. Maybe we don't need to 222 | # set temp_path at all? 223 | # 224 | # attachment.temp_paths.unshift File.join(fixture_path, file) 225 | attachment.save! 226 | end 227 | end 228 | end 229 | 230 | test_against_subclass :test_should_overwrite_old_thumbnail_records_when_updating, ImageWithThumbsAttachment 231 | 232 | def test_should_overwrite_old_thumbnail_records_when_renaming(klass = ImageWithThumbsAttachment) 233 | attachment_model klass 234 | attachment = nil 235 | assert_created 3 do 236 | attachment = upload_file :class => klass, :filename => '/files/rails.png' 237 | end 238 | assert_not_created do # no new db_file records 239 | attachment.filename = 'rails2.png' 240 | attachment.save 241 | assert !attachment.reload.size.zero? 242 | assert_equal 'rails2.png', attachment.filename 243 | end 244 | end 245 | 246 | test_against_subclass :test_should_overwrite_old_thumbnail_records_when_renaming, ImageWithThumbsAttachment 247 | else 248 | def test_flunk 249 | puts "RMagick not installed, no tests running" 250 | end 251 | end 252 | end 253 | -------------------------------------------------------------------------------- /lib/technoweenie/attachment_fu/backends/s3_backend.rb: -------------------------------------------------------------------------------- 1 | module Technoweenie # :nodoc: 2 | module AttachmentFu # :nodoc: 3 | module Backends 4 | # = AWS::S3 Storage Backend 5 | # 6 | # Enables use of {Amazon's Simple Storage Service}[http://aws.amazon.com/s3] as a storage mechanism 7 | # 8 | # == Requirements 9 | # 10 | # Requires the {AWS::S3 Library}[http://amazon.rubyforge.org] for S3 by Marcel Molina Jr. installed either 11 | # as a gem or a as a Rails plugin. 12 | # 13 | # == Configuration 14 | # 15 | # Configuration is done via RAILS_ROOT/config/amazon_s3.yml and is loaded according to the RAILS_ENV. 16 | # The minimum connection options that you must specify are a bucket name, your access key id and your secret access key. 17 | # If you don't already have your access keys, all you need to sign up for the S3 service is an account at Amazon. 18 | # You can sign up for S3 and get access keys by visiting http://aws.amazon.com/s3. 19 | # 20 | # Example configuration (RAILS_ROOT/config/amazon_s3.yml) 21 | # 22 | # development: 23 | # bucket_name: appname_development 24 | # access_key_id: 25 | # secret_access_key: 26 | # 27 | # test: 28 | # bucket_name: appname_test 29 | # access_key_id: 30 | # secret_access_key: 31 | # 32 | # production: 33 | # bucket_name: appname 34 | # access_key_id: 35 | # secret_access_key: 36 | # 37 | # You can change the location of the config path by passing a full path to the :s3_config_path option. 38 | # 39 | # has_attachment :storage => :s3, :s3_config_path => (RAILS_ROOT + '/config/s3.yml') 40 | # 41 | # === Required configuration parameters 42 | # 43 | # * :access_key_id - The access key id for your S3 account. Provided by Amazon. 44 | # * :secret_access_key - The secret access key for your S3 account. Provided by Amazon. 45 | # * :bucket_name - A unique bucket name (think of the bucket_name as being like a database name). 46 | # 47 | # If any of these required arguments is missing, a MissingAccessKey exception will be raised from AWS::S3. 48 | # 49 | # == About bucket names 50 | # 51 | # Bucket names have to be globaly unique across the S3 system. And you can only have up to 100 of them, 52 | # so it's a good idea to think of a bucket as being like a database, hence the correspondance in this 53 | # implementation to the development, test, and production environments. 54 | # 55 | # The number of objects you can store in a bucket is, for all intents and purposes, unlimited. 56 | # 57 | # === Optional configuration parameters 58 | # 59 | # * :server - The server to make requests to. Defaults to s3.amazonaws.com. 60 | # * :port - The port to the requests should be made on. Defaults to 80 or 443 if :use_ssl is set. 61 | # * :use_ssl - If set to true, :port will be implicitly set to 443, unless specified otherwise. Defaults to false. 62 | # 63 | # == Usage 64 | # 65 | # To specify S3 as the storage mechanism for a model, set the acts_as_attachment :storage option to :s3. 66 | # 67 | # class Photo < ActiveRecord::Base 68 | # has_attachment :storage => :s3 69 | # end 70 | # 71 | # === Customizing the path 72 | # 73 | # By default, files are prefixed using a pseudo hierarchy in the form of :table_name/:id, which results 74 | # in S3 urls that look like: http(s)://:server/:bucket_name/:table_name/:id/:filename with :table_name 75 | # representing the customizable portion of the path. You can customize this prefix using the :path_prefix 76 | # option: 77 | # 78 | # class Photo < ActiveRecord::Base 79 | # has_attachment :storage => :s3, :path_prefix => 'my/custom/path' 80 | # end 81 | # 82 | # Which would result in URLs like http(s)://:server/:bucket_name/my/custom/path/:id/:filename. 83 | # 84 | # === Using different bucket names on different models 85 | # 86 | # By default the bucket name that the file will be stored to is the one specified by the 87 | # :bucket_name key in the amazon_s3.yml file. You can use the :bucket_key option 88 | # to overide this behavior on a per model basis. For instance if you want a bucket that will hold 89 | # only Photos you can do this: 90 | # 91 | # class Photo < ActiveRecord::Base 92 | # has_attachment :storage => :s3, :bucket_key => :photo_bucket_name 93 | # end 94 | # 95 | # And then your amazon_s3.yml file needs to look like this. 96 | # 97 | # development: 98 | # bucket_name: appname_development 99 | # access_key_id: 100 | # secret_access_key: 101 | # 102 | # test: 103 | # bucket_name: appname_test 104 | # access_key_id: 105 | # secret_access_key: 106 | # 107 | # production: 108 | # bucket_name: appname 109 | # photo_bucket_name: appname_photos 110 | # access_key_id: 111 | # secret_access_key: 112 | # 113 | # If the bucket_key you specify is not there in a certain environment then attachment_fu will 114 | # default to the bucket_name key. This way you only have to create special buckets 115 | # this can be helpful if you only need special buckets in certain environments. 116 | # 117 | # === Permissions 118 | # 119 | # By default, files are stored on S3 with public access permissions. You can customize this using 120 | # the :s3_access option to has_attachment. Available values are 121 | # :private, :public_read_write, and :authenticated_read. 122 | # 123 | # === Other options 124 | # 125 | # Of course, all the usual configuration options apply, such as content_type and thumbnails: 126 | # 127 | # class Photo < ActiveRecord::Base 128 | # has_attachment :storage => :s3, :content_type => ['application/pdf', :image], :resize_to => 'x50' 129 | # has_attachment :storage => :s3, :thumbnails => { :thumb => [50, 50], :geometry => 'x50' } 130 | # end 131 | # 132 | # === Accessing S3 URLs 133 | # 134 | # You can get an object's URL using the s3_url accessor. For example, assuming that for your postcard app 135 | # you had a bucket name like 'postcard_world_development', and an attachment model called Photo: 136 | # 137 | # @postcard.s3_url # => http(s)://s3.amazonaws.com/postcard_world_development/photos/1/mexico.jpg 138 | # 139 | # The resulting url is in the form: http(s)://:server/:bucket_name/:table_name/:id/:file. 140 | # The optional thumbnail argument will output the thumbnail's filename (if any). 141 | # 142 | # Additionally, you can get an object's base path relative to the bucket root using 143 | # base_path: 144 | # 145 | # @photo.file_base_path # => photos/1 146 | # 147 | # And the full path (including the filename) using full_filename: 148 | # 149 | # @photo.full_filename # => photos/ 150 | # 151 | # Niether base_path or full_filename include the bucket name as part of the path. 152 | # You can retrieve the bucket name using the bucket_name method. 153 | module S3Backend 154 | class RequiredLibraryNotFoundError < StandardError; end 155 | class ConfigFileNotFoundError < StandardError; end 156 | 157 | def self.included(base) #:nodoc: 158 | mattr_reader :bucket_name, :s3_config 159 | 160 | begin 161 | require 'aws/s3' 162 | include AWS::S3 163 | rescue LoadError 164 | raise RequiredLibraryNotFoundError.new('AWS::S3 could not be loaded') 165 | end 166 | 167 | begin 168 | @@s3_config_path = base.attachment_options[:s3_config_path] || (RAILS_ROOT + '/config/amazon_s3.yml') 169 | @@s3_config = @@s3_config = YAML.load(ERB.new(File.read(@@s3_config_path)).result)[RAILS_ENV].symbolize_keys 170 | #rescue 171 | # raise ConfigFileNotFoundError.new('File %s not found' % @@s3_config_path) 172 | end 173 | 174 | bucket_key = base.attachment_options[:bucket_key] 175 | 176 | if bucket_key and s3_config[bucket_key.to_sym] 177 | eval_string = "def bucket_name()\n \"#{s3_config[bucket_key.to_sym]}\"\nend" 178 | else 179 | eval_string = "def bucket_name()\n \"#{s3_config[:bucket_name]}\"\nend" 180 | end 181 | base.class_eval(eval_string, __FILE__, __LINE__) 182 | 183 | Base.establish_connection!(s3_config.slice(:access_key_id, :secret_access_key, :server, :port, :use_ssl, :persistent, :proxy)) 184 | 185 | # Bucket.create(@@bucket_name) 186 | 187 | base.before_update :rename_file 188 | end 189 | 190 | def self.protocol 191 | @protocol ||= s3_config[:use_ssl] ? 'https://' : 'http://' 192 | end 193 | 194 | def self.hostname 195 | @hostname ||= s3_config[:server] || AWS::S3::DEFAULT_HOST 196 | end 197 | 198 | def self.port_string 199 | @port_string ||= (s3_config[:port].nil? || s3_config[:port] == (s3_config[:use_ssl] ? 443 : 80)) ? '' : ":#{s3_config[:port]}" 200 | end 201 | 202 | module ClassMethods 203 | def s3_protocol 204 | Technoweenie::AttachmentFu::Backends::S3Backend.protocol 205 | end 206 | 207 | def s3_hostname 208 | Technoweenie::AttachmentFu::Backends::S3Backend.hostname 209 | end 210 | 211 | def s3_port_string 212 | Technoweenie::AttachmentFu::Backends::S3Backend.port_string 213 | end 214 | end 215 | 216 | # Overwrites the base filename writer in order to store the old filename 217 | def filename=(value) 218 | @old_filename = filename unless filename.nil? || @old_filename 219 | write_attribute :filename, sanitize_filename(value) 220 | end 221 | 222 | # The attachment ID used in the full path of a file 223 | def attachment_path_id 224 | ((respond_to?(:parent_id) && parent_id) || id).to_s 225 | end 226 | 227 | # The pseudo hierarchy containing the file relative to the bucket name 228 | # Example: :table_name/:id 229 | def base_path 230 | File.join(attachment_options[:path_prefix], attachment_path_id) 231 | end 232 | 233 | # The full path to the file relative to the bucket name 234 | # Example: :table_name/:id/:filename 235 | def full_filename(thumbnail = nil) 236 | File.join(base_path, thumbnail_name_for(thumbnail)) 237 | end 238 | 239 | # All public objects are accessible via a GET request to the S3 servers. You can generate a 240 | # url for an object using the s3_url method. 241 | # 242 | # @photo.s3_url 243 | # 244 | # The resulting url is in the form: http(s)://:server/:bucket_name/:table_name/:id/:file where 245 | # the :server variable defaults to AWS::S3 URL::DEFAULT_HOST (s3.amazonaws.com) and can be 246 | # set using the configuration parameters in RAILS_ROOT/config/amazon_s3.yml. 247 | # 248 | # The optional thumbnail argument will output the thumbnail's filename (if any). 249 | def s3_url(thumbnail = nil) 250 | File.join(s3_protocol + s3_hostname + s3_port_string, bucket_name, full_filename(thumbnail)) 251 | end 252 | alias :public_filename :s3_url 253 | 254 | # All private objects are accessible via an authenticated GET request to the S3 servers. You can generate an 255 | # authenticated url for an object like this: 256 | # 257 | # @photo.authenticated_s3_url 258 | # 259 | # By default authenticated urls expire 5 minutes after they were generated. 260 | # 261 | # Expiration options can be specified either with an absolute time using the :expires option, 262 | # or with a number of seconds relative to now with the :expires_in option: 263 | # 264 | # # Absolute expiration date (October 13th, 2025) 265 | # @photo.authenticated_s3_url(:expires => Time.mktime(2025,10,13).to_i) 266 | # 267 | # # Expiration in five hours from now 268 | # @photo.authenticated_s3_url(:expires_in => 5.hours) 269 | # 270 | # You can specify whether the url should go over SSL with the :use_ssl option. 271 | # By default, the ssl settings for the current connection will be used: 272 | # 273 | # @photo.authenticated_s3_url(:use_ssl => true) 274 | # 275 | # Finally, the optional thumbnail argument will output the thumbnail's filename (if any): 276 | # 277 | # @photo.authenticated_s3_url('thumbnail', :expires_in => 5.hours, :use_ssl => true) 278 | def authenticated_s3_url(*args) 279 | options = args.extract_options! 280 | options[:expires_in] = options[:expires_in].to_i if options[:expires_in] 281 | thumbnail = args.shift 282 | S3Object.url_for(full_filename(thumbnail), bucket_name, options) 283 | end 284 | 285 | def create_temp_file 286 | write_to_temp_file current_data 287 | end 288 | 289 | def current_data 290 | S3Object.value full_filename, bucket_name 291 | end 292 | 293 | def s3_protocol 294 | Technoweenie::AttachmentFu::Backends::S3Backend.protocol 295 | end 296 | 297 | def s3_hostname 298 | Technoweenie::AttachmentFu::Backends::S3Backend.hostname 299 | end 300 | 301 | def s3_port_string 302 | Technoweenie::AttachmentFu::Backends::S3Backend.port_string 303 | end 304 | 305 | protected 306 | # Called in the after_destroy callback 307 | def destroy_file 308 | S3Object.delete full_filename, bucket_name 309 | end 310 | 311 | def rename_file 312 | return unless @old_filename && @old_filename != filename 313 | 314 | old_full_filename = File.join(base_path, @old_filename) 315 | 316 | S3Object.rename( 317 | old_full_filename, 318 | full_filename, 319 | bucket_name, 320 | :access => attachment_options[:s3_access] 321 | ) 322 | 323 | @old_filename = nil 324 | true 325 | end 326 | 327 | def save_to_storage 328 | if save_attachment? 329 | S3Object.store( 330 | full_filename, 331 | (temp_path ? File.open(temp_path) : temp_data), 332 | bucket_name, 333 | :content_type => content_type, 334 | :access => attachment_options[:s3_access] 335 | ) 336 | end 337 | 338 | @old_filename = nil 339 | true 340 | end 341 | end 342 | end 343 | end 344 | end 345 | -------------------------------------------------------------------------------- /lib/technoweenie/attachment_fu.rb: -------------------------------------------------------------------------------- 1 | module Technoweenie # :nodoc: 2 | module AttachmentFu # :nodoc: 3 | @@default_processors = %w(ImageScience Rmagick MiniMagick Gd2 CoreImage) 4 | @@tempfile_path = File.join(RAILS_ROOT, 'tmp', 'attachment_fu') 5 | @@content_types = [ 6 | 'image/jpeg', 7 | 'image/pjpeg', 8 | 'image/jpg', 9 | 'image/gif', 10 | 'image/png', 11 | 'image/x-png', 12 | 'image/jpg', 13 | 'image/x-ms-bmp', 14 | 'image/bmp', 15 | 'image/x-bmp', 16 | 'image/x-bitmap', 17 | 'image/x-xbitmap', 18 | 'image/x-win-bitmap', 19 | 'image/x-windows-bmp', 20 | 'image/ms-bmp', 21 | 'application/bmp', 22 | 'application/x-bmp', 23 | 'application/x-win-bitmap', 24 | 'application/preview', 25 | 'image/jp_', 26 | 'application/jpg', 27 | 'application/x-jpg', 28 | 'image/pipeg', 29 | 'image/vnd.swiftview-jpeg', 30 | 'image/x-xbitmap', 31 | 'application/png', 32 | 'application/x-png', 33 | 'image/gi_', 34 | 'image/x-citrix-pjpeg' 35 | ] 36 | mattr_reader :content_types, :tempfile_path, :default_processors 37 | mattr_writer :tempfile_path 38 | 39 | class ThumbnailError < StandardError; end 40 | class AttachmentError < StandardError; end 41 | 42 | module ActMethods 43 | # Options: 44 | # * :content_type - Allowed content types. Allows all by default. Use :image to allow all standard image types. 45 | # * :min_size - Minimum size allowed. 1 byte is the default. 46 | # * :max_size - Maximum size allowed. 1.megabyte is the default. 47 | # * :size - Range of sizes allowed. (1..1.megabyte) is the default. This overrides the :min_size and :max_size options. 48 | # * :resize_to - Used by RMagick to resize images. Pass either an array of width/height, or a geometry string. 49 | # * :thumbnails - Specifies a set of thumbnails to generate. This accepts a hash of filename suffixes and RMagick resizing options. 50 | # * :thumbnail_class - Set what class to use for thumbnails. This attachment class is used by default. 51 | # * :path_prefix - path to store the uploaded files. Uses public/#{table_name} by default for the filesystem, and just #{table_name} 52 | # for the S3 backend. Setting this sets the :storage to :file_system. 53 | 54 | # * :storage - Use :file_system to specify the attachment data is stored with the file system. Defaults to :db_system. 55 | # * :bucket_key - Use this to specify a different bucket key other than :bucket_name in the amazon_s3.yml file. This allows you to use 56 | # different buckets for different models. An example setting would be :image_bucket and the you would need to define the name of the corresponding 57 | # bucket in the amazon_s3.yml file. 58 | 59 | # * :keep_profile 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. 60 | # 61 | # Examples: 62 | # has_attachment :max_size => 1.kilobyte 63 | # has_attachment :size => 1.megabyte..2.megabytes 64 | # has_attachment :content_type => 'application/pdf' 65 | # has_attachment :content_type => ['application/pdf', 'application/msword', 'text/plain'] 66 | # has_attachment :content_type => :image, :resize_to => [50,50] 67 | # has_attachment :content_type => ['application/pdf', :image], :resize_to => 'x50' 68 | # has_attachment :thumbnails => { :thumb => [50, 50], :geometry => 'x50' } 69 | # has_attachment :storage => :file_system, :path_prefix => 'public/files' 70 | # has_attachment :storage => :file_system, :path_prefix => 'public/files', 71 | # :content_type => :image, :resize_to => [50,50] 72 | # has_attachment :storage => :file_system, :path_prefix => 'public/files', 73 | # :thumbnails => { :thumb => [50, 50], :geometry => 'x50' } 74 | # has_attachment :storage => :s3 75 | def has_attachment(options = {}) 76 | # this allows you to redefine the acts' options for each subclass, however 77 | options[:min_size] ||= 1 78 | options[:max_size] ||= 1.megabyte 79 | options[:size] ||= (options[:min_size]..options[:max_size]) 80 | options[:thumbnails] ||= {} 81 | options[:thumbnail_class] ||= self 82 | options[:s3_access] ||= :public_read 83 | options[:content_type] = [options[:content_type]].flatten.collect! { |t| t == :image ? Technoweenie::AttachmentFu.content_types : t }.flatten unless options[:content_type].nil? 84 | 85 | unless options[:thumbnails].is_a?(Hash) 86 | raise ArgumentError, ":thumbnails option should be a hash: e.g. :thumbnails => { :foo => '50x50' }" 87 | end 88 | 89 | extend ClassMethods unless (class << self; included_modules; end).include?(ClassMethods) 90 | include InstanceMethods unless included_modules.include?(InstanceMethods) 91 | 92 | parent_options = attachment_options || {} 93 | # doing these shenanigans so that #attachment_options is available to processors and backends 94 | self.attachment_options = options 95 | 96 | attr_accessor :thumbnail_resize_options 97 | 98 | attachment_options[:storage] ||= (attachment_options[:file_system_path] || attachment_options[:path_prefix]) ? :file_system : :db_file 99 | attachment_options[:storage] ||= parent_options[:storage] 100 | attachment_options[:path_prefix] ||= attachment_options[:file_system_path] 101 | if attachment_options[:path_prefix].nil? 102 | attachment_options[:path_prefix] = attachment_options[:storage] == :s3 ? table_name : File.join("public", table_name) 103 | end 104 | attachment_options[:path_prefix] = attachment_options[:path_prefix][1..-1] if options[:path_prefix].first == '/' 105 | 106 | association_options = { :foreign_key => 'parent_id' } 107 | if attachment_options[:association_options] 108 | association_options.merge!(attachment_options[:association_options]) 109 | end 110 | with_options(association_options) do |m| 111 | m.has_many :thumbnails, :class_name => "::#{attachment_options[:thumbnail_class]}" 112 | m.belongs_to :parent, :class_name => "::#{base_class}" unless options[:thumbnails].empty? 113 | end 114 | 115 | storage_mod = Technoweenie::AttachmentFu::Backends.const_get("#{options[:storage].to_s.classify}Backend") 116 | include storage_mod unless included_modules.include?(storage_mod) 117 | 118 | case attachment_options[:processor] 119 | when :none, nil 120 | processors = Technoweenie::AttachmentFu.default_processors.dup 121 | begin 122 | if processors.any? 123 | attachment_options[:processor] = processors.first 124 | processor_mod = Technoweenie::AttachmentFu::Processors.const_get("#{attachment_options[:processor].to_s.classify}Processor") 125 | include processor_mod unless included_modules.include?(processor_mod) 126 | end 127 | rescue Object, Exception 128 | raise unless load_related_exception?($!) 129 | 130 | processors.shift 131 | retry 132 | end 133 | else 134 | begin 135 | processor_mod = Technoweenie::AttachmentFu::Processors.const_get("#{attachment_options[:processor].to_s.classify}Processor") 136 | include processor_mod unless included_modules.include?(processor_mod) 137 | rescue Object, Exception 138 | raise unless load_related_exception?($!) 139 | 140 | puts "Problems loading #{options[:processor]}Processor: #{$!}" 141 | end 142 | end unless parent_options[:processor] # Don't let child override processor 143 | end 144 | 145 | def load_related_exception?(e) #:nodoc: implementation specific 146 | case 147 | when e.kind_of?(LoadError), e.kind_of?(MissingSourceFile), $!.class.name == "CompilationError" 148 | # We can't rescue CompilationError directly, as it is part of the RubyInline library. 149 | # We must instead rescue RuntimeError, and check the class' name. 150 | true 151 | else 152 | false 153 | end 154 | end 155 | private :load_related_exception? 156 | end 157 | 158 | module ClassMethods 159 | delegate :content_types, :to => Technoweenie::AttachmentFu 160 | 161 | # Performs common validations for attachment models. 162 | def validates_as_attachment 163 | validates_presence_of :size, :content_type, :filename 164 | validate :attachment_attributes_valid? 165 | end 166 | 167 | # Returns true or false if the given content type is recognized as an image. 168 | def image?(content_type) 169 | content_types.include?(content_type) 170 | end 171 | 172 | def self.extended(base) 173 | base.class_inheritable_accessor :attachment_options 174 | base.before_destroy :destroy_thumbnails 175 | base.before_validation :set_size_from_temp_path 176 | base.after_save :after_process_attachment 177 | base.after_destroy :destroy_file 178 | base.after_validation :process_attachment 179 | base.attr_accessible :uploaded_data 180 | if defined?(::ActiveSupport::Callbacks) 181 | base.define_callbacks :after_resize, :after_attachment_saved, :before_thumbnail_saved 182 | end 183 | end 184 | 185 | unless defined?(::ActiveSupport::Callbacks) 186 | # Callback after an image has been resized. 187 | # 188 | # class Foo < ActiveRecord::Base 189 | # acts_as_attachment 190 | # after_resize do |record, img| 191 | # record.aspect_ratio = img.columns.to_f / img.rows.to_f 192 | # end 193 | # end 194 | def after_resize(&block) 195 | write_inheritable_array(:after_resize, [block]) 196 | end 197 | 198 | # Callback after an attachment has been saved either to the file system or the DB. 199 | # Only called if the file has been changed, not necessarily if the record is updated. 200 | # 201 | # class Foo < ActiveRecord::Base 202 | # acts_as_attachment 203 | # after_attachment_saved do |record| 204 | # ... 205 | # end 206 | # end 207 | def after_attachment_saved(&block) 208 | write_inheritable_array(:after_attachment_saved, [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 | returning Tempfile.new(temp_base_name, Technoweenie::AttachmentFu.tempfile_path) 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 | returning Tempfile.new(temp_base_name, Technoweenie::AttachmentFu.tempfile_path) 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 | base.define_callbacks *[:after_resize, :after_attachment_saved, :before_thumbnail_saved] if base.respond_to?(:define_callbacks) 253 | end 254 | 255 | # Checks whether the attachment's content type is an image content type 256 | def image? 257 | self.class.image?(content_type) 258 | end 259 | 260 | # Returns true/false if an attachment is thumbnailable. A thumbnailable attachment has an image content type and the parent_id attribute. 261 | def thumbnailable? 262 | image? && respond_to?(:parent_id) && parent_id.nil? 263 | end 264 | 265 | # Returns the class used to create new thumbnails for this attachment. 266 | def thumbnail_class 267 | self.class.thumbnail_class 268 | end 269 | 270 | # Gets the thumbnail name for a filename. 'foo.jpg' becomes 'foo_thumbnail.jpg' 271 | def thumbnail_name_for(thumbnail = nil) 272 | return filename if thumbnail.blank? 273 | ext = nil 274 | basename = filename.gsub /\.\w+$/ do |s| 275 | ext = s; '' 276 | end 277 | # ImageScience doesn't create gif thumbnails, only pngs 278 | ext.sub!(/gif$/, 'png') if attachment_options[:processor] == "ImageScience" 279 | "#{basename}_#{thumbnail}#{ext}" 280 | end 281 | 282 | # Creates or updates the thumbnail for the current attachment. 283 | def create_or_update_thumbnail(temp_file, file_name_suffix, *size) 284 | thumbnailable? || raise(ThumbnailError.new("Can't create a thumbnail if the content type is not an image or there is no parent_id column")) 285 | returning find_or_initialize_thumbnail(file_name_suffix) do |thumb| 286 | thumb.temp_paths.unshift temp_file 287 | thumb.send(:'attributes=', { 288 | :content_type => content_type, 289 | :filename => thumbnail_name_for(file_name_suffix), 290 | :thumbnail_resize_options => size, 291 | :crop_x => crop_x, 292 | :crop_y => crop_y, 293 | :crop_width => crop_width, 294 | :crop_height => crop_height 295 | }, false) 296 | callback_with_args :before_thumbnail_saved, thumb 297 | thumb.save! 298 | end 299 | end 300 | 301 | # Sets the content type. 302 | def content_type=(new_type) 303 | write_attribute :content_type, new_type.to_s.strip 304 | end 305 | 306 | # Sanitizes a filename. 307 | def filename=(new_name) 308 | write_attribute :filename, sanitize_filename(new_name) 309 | end 310 | 311 | # Returns the width/height in a suitable format for the image_tag helper: (100x100) 312 | def image_size 313 | [width.to_s, height.to_s] * 'x' 314 | end 315 | 316 | # Returns true if the attachment data will be written to the storage system on the next save 317 | def save_attachment? 318 | File.file?(temp_path.to_s) 319 | end 320 | 321 | # nil placeholder in case this field is used in a form. 322 | def uploaded_data() nil; end 323 | 324 | # This method handles the uploaded file object. If you set the field name to uploaded_data, you don't need 325 | # any special code in your controller. 326 | # 327 | # <% form_for :attachment, :html => { :multipart => true } do |f| -%> 328 | #

<%= f.file_field :uploaded_data %>

329 | #

<%= submit_tag :Save %> 330 | # <% end -%> 331 | # 332 | # @attachment = Attachment.create! params[:attachment] 333 | # 334 | # TODO: Allow it to work with Merb tempfiles too. 335 | def uploaded_data=(file_data) 336 | if file_data.respond_to?(:content_type) 337 | return nil if file_data.size == 0 338 | self.content_type = file_data.content_type 339 | self.filename = file_data.original_filename if respond_to?(:filename) 340 | else 341 | return nil if file_data.blank? || file_data['size'] == 0 342 | self.content_type = file_data['content_type'] 343 | self.filename = file_data['filename'] 344 | file_data = file_data['tempfile'] 345 | end 346 | if file_data.is_a?(StringIO) 347 | file_data.rewind 348 | set_temp_data file_data.read 349 | else 350 | self.temp_paths.unshift file_data 351 | end 352 | end 353 | 354 | # Gets the latest temp path from the collection of temp paths. While working with an attachment, 355 | # multiple Tempfile objects may be created for various processing purposes (resizing, for example). 356 | # An array of all the tempfile objects is stored so that the Tempfile instance is held on to until 357 | # it's not needed anymore. The collection is cleared after saving the attachment. 358 | def temp_path 359 | p = temp_paths.first 360 | p.respond_to?(:path) ? p.path : p.to_s 361 | end 362 | 363 | # Gets an array of the currently used temp paths. Defaults to a copy of #full_filename. 364 | def temp_paths 365 | @temp_paths ||= (new_record? || !respond_to?(:full_filename) || !File.exist?(full_filename) ? 366 | [] : [copy_to_temp_file(full_filename)]) 367 | end 368 | 369 | # Gets the data from the latest temp file. This will read the file into memory. 370 | def temp_data 371 | save_attachment? ? File.read(temp_path) : nil 372 | end 373 | 374 | # Writes the given data to a Tempfile and adds it to the collection of temp files. 375 | def set_temp_data(data) 376 | temp_paths.unshift write_to_temp_file data unless data.nil? 377 | end 378 | 379 | # Copies the given file to a randomly named Tempfile. 380 | def copy_to_temp_file(file) 381 | self.class.copy_to_temp_file file, random_tempfile_filename 382 | end 383 | 384 | # Writes the given file to a randomly named Tempfile. 385 | def write_to_temp_file(data) 386 | self.class.write_to_temp_file data, random_tempfile_filename 387 | end 388 | 389 | # Stub for creating a temp file from the attachment data. This should be defined in the backend module. 390 | def create_temp_file() end 391 | 392 | # Allows you to work with a processed representation (RMagick, ImageScience, etc) of the attachment in a block. 393 | # 394 | # @attachment.with_image do |img| 395 | # self.data = img.thumbnail(100, 100).to_blob 396 | # end 397 | # 398 | def with_image(&block) 399 | self.class.with_image(temp_path, &block) 400 | end 401 | 402 | def crop_x 403 | read_attribute(:crop_x) || 0 404 | end 405 | 406 | def crop_y 407 | read_attribute(:crop_y) || 0 408 | end 409 | 410 | def crop_width 411 | read_attribute(:crop_width) || read_attribute(:width) 412 | end 413 | 414 | def crop_height 415 | read_attribute(:crop_height) || read_attribute(:height) 416 | end 417 | 418 | protected 419 | # Generates a unique filename for a Tempfile. 420 | def random_tempfile_filename 421 | "#{rand Time.now.to_i}#{filename || 'attachment'}" 422 | end 423 | 424 | def sanitize_filename(filename) 425 | return unless filename 426 | returning filename.strip do |name| 427 | # NOTE: File.basename doesn't work right with Windows paths on Unix 428 | # get only the filename, not the whole path 429 | name.gsub! /^.*(\\|\/)/, '' 430 | 431 | # Finally, replace all non alphanumeric, underscore or periods with underscore 432 | name.gsub! /[^A-Za-z0-9\.\-]/, '_' 433 | end 434 | end 435 | 436 | # before_validation callback. 437 | def set_size_from_temp_path 438 | self.size = File.size(temp_path) if save_attachment? 439 | end 440 | 441 | # validates the size and content_type attributes according to the current model's options 442 | def attachment_attributes_valid? 443 | [:size, :content_type].each do |attr_name| 444 | enum = attachment_options[attr_name] 445 | if Object.const_defined?(:I18n) # Rails >= 2.2 446 | errors.add attr_name, I18n.translate("activerecord.errors.messages.inclusion", attr_name => enum) unless enum.nil? || enum.include?(send(attr_name)) 447 | else 448 | errors.add attr_name, ActiveRecord::Errors.default_error_messages[:inclusion] unless enum.nil? || enum.include?(send(attr_name)) 449 | end 450 | end 451 | end 452 | 453 | # Initializes a new thumbnail with the given suffix. 454 | def find_or_initialize_thumbnail(file_name_suffix) 455 | respond_to?(:parent_id) ? 456 | thumbnail_class.find_or_initialize_by_thumbnail_and_parent_id(file_name_suffix.to_s, id) : 457 | thumbnail_class.find_or_initialize_by_thumbnail(file_name_suffix.to_s) 458 | end 459 | 460 | # Stub for a #process_attachment method in a processor 461 | def process_attachment 462 | @saved_attachment = save_attachment? 463 | end 464 | 465 | # Cleans up after processing. Thumbnails are created, the attachment is stored to the backend, and the temp_paths are cleared. 466 | def after_process_attachment 467 | if @saved_attachment 468 | if respond_to?(:process_attachment_with_processing) && thumbnailable? && !attachment_options[:thumbnails].blank? && parent_id.nil? 469 | temp_file = temp_path || create_temp_file 470 | attachment_options[:thumbnails].each { |suffix, size| create_or_update_thumbnail(temp_file, suffix, *size) } 471 | end 472 | save_to_storage 473 | @temp_paths.clear 474 | @saved_attachment = nil 475 | callback :after_attachment_saved 476 | end 477 | end 478 | 479 | # Resizes the given processed img object with either the attachment resize options or the thumbnail resize options. 480 | def resize_image_or_thumbnail!(img) 481 | if (!respond_to?(:parent_id) || parent_id.nil?) && attachment_options[:resize_to] # parent image 482 | resize_image(img, attachment_options[:resize_to]) 483 | elsif thumbnail_resize_options # thumbnail 484 | resize_image(img, thumbnail_resize_options) 485 | end 486 | end 487 | 488 | # Yanked from ActiveRecord::Callbacks, modified so I can pass args to the callbacks besides self. 489 | # Only accept blocks, however 490 | if ActiveSupport.const_defined?(:Callbacks) 491 | # Rails 2.1 and beyond! 492 | def callback_with_args(method, arg = self) 493 | notify(method) 494 | 495 | result = run_callbacks(method, { :object => arg }) { |result, object| result == false } 496 | 497 | if result != false && respond_to_without_attributes?(method) 498 | result = send(method) 499 | end 500 | 501 | result 502 | end 503 | 504 | def run_callbacks(kind, options = {}, &block) 505 | options.reverse_merge!( :object => self ) 506 | self.class.send("#{kind}_callback_chain").run(options[:object], options, &block) 507 | end 508 | else 509 | # Rails 2.0 510 | def callback_with_args(method, arg = self) 511 | notify(method) 512 | 513 | result = nil 514 | callbacks_for(method).each do |callback| 515 | result = callback.call(self, arg) 516 | return false if result == false 517 | end 518 | result 519 | end 520 | end 521 | 522 | # Removes the thumbnails for the attachment, if it has any 523 | def destroy_thumbnails 524 | self.thumbnails.each { |thumbnail| thumbnail.destroy } if thumbnailable? 525 | end 526 | end 527 | end 528 | end 529 | --------------------------------------------------------------------------------