]> projects.mako.cc - selectricity/commitdiff
updated top the the new version of attachment_fu plugin to work out some
authorBenjamin Mako Hill <mako@atdot.cc>
Tue, 16 Jun 2009 21:10:32 +0000 (17:10 -0400)
committerBenjamin Mako Hill <mako@atdot.cc>
Tue, 16 Jun 2009 21:10:32 +0000 (17:10 -0400)
rails 2.2 issues

42 files changed:
config/amazon_s3.yml [new file with mode: 0644]
config/rackspace_cloudfiles.yml [new file with mode: 0644]
vendor/plugins/attachment_fu/.gitignore [new file with mode: 0644]
vendor/plugins/attachment_fu/CHANGELOG
vendor/plugins/attachment_fu/LICENSE [new file with mode: 0644]
vendor/plugins/attachment_fu/README
vendor/plugins/attachment_fu/amazon_s3.yml.tpl
vendor/plugins/attachment_fu/init.rb
vendor/plugins/attachment_fu/install.rb
vendor/plugins/attachment_fu/lib/geometry.rb
vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu.rb
vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu/backends/cloud_file_backend.rb [new file with mode: 0644]
vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu/backends/file_system_backend.rb
vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu/backends/s3_backend.rb
vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu/processors/core_image_processor.rb [new file with mode: 0644]
vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu/processors/gd2_processor.rb [new file with mode: 0644]
vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu/processors/image_science_processor.rb
vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu/processors/mini_magick_processor.rb
vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu/processors/rmagick_processor.rb
vendor/plugins/attachment_fu/rackspace_cloudfiles.yml.tpl [new file with mode: 0644]
vendor/plugins/attachment_fu/test/amazon_s3.yml [deleted file]
vendor/plugins/attachment_fu/test/backends/file_system_test.rb
vendor/plugins/attachment_fu/test/backends/remote/cloudfiles_test.rb [new file with mode: 0644]
vendor/plugins/attachment_fu/test/backends/remote/s3_test.rb
vendor/plugins/attachment_fu/test/base_attachment_tests.rb
vendor/plugins/attachment_fu/test/basic_test.rb
vendor/plugins/attachment_fu/test/extra_attachment_test.rb
vendor/plugins/attachment_fu/test/fixtures/attachment.rb
vendor/plugins/attachment_fu/test/geometry_test.rb
vendor/plugins/attachment_fu/test/processors/core_image_test.rb [new file with mode: 0644]
vendor/plugins/attachment_fu/test/processors/gd2_test.rb [new file with mode: 0644]
vendor/plugins/attachment_fu/test/processors/mini_magick_test.rb
vendor/plugins/attachment_fu/test/processors/rmagick_test.rb
vendor/plugins/attachment_fu/test/schema.rb
vendor/plugins/attachment_fu/test/test_helper.rb
vendor/plugins/attachment_fu/vendor/red_artisan/core_image/filters/color.rb [new file with mode: 0644]
vendor/plugins/attachment_fu/vendor/red_artisan/core_image/filters/effects.rb [new file with mode: 0644]
vendor/plugins/attachment_fu/vendor/red_artisan/core_image/filters/perspective.rb [new file with mode: 0644]
vendor/plugins/attachment_fu/vendor/red_artisan/core_image/filters/quality.rb [new file with mode: 0644]
vendor/plugins/attachment_fu/vendor/red_artisan/core_image/filters/scale.rb [new file with mode: 0644]
vendor/plugins/attachment_fu/vendor/red_artisan/core_image/filters/watermark.rb [new file with mode: 0644]
vendor/plugins/attachment_fu/vendor/red_artisan/core_image/processor.rb [new file with mode: 0644]

diff --git a/config/amazon_s3.yml b/config/amazon_s3.yml
new file mode 100644 (file)
index 0000000..5c585e7
--- /dev/null
@@ -0,0 +1,17 @@
+development:
+  bucket_name: appname_development
+  access_key_id: 
+  secret_access_key: 
+  distribution_domain: XXXX.cloudfront.net
+
+test:
+  bucket_name: appname_test
+  access_key_id: 
+  secret_access_key: 
+  distribution_domain: XXXX.cloudfront.net
+
+production:
+  bucket_name: appname
+  access_key_id: 
+  secret_access_key: 
+  distribution_domain: XXXX.cloudfront.net
diff --git a/config/rackspace_cloudfiles.yml b/config/rackspace_cloudfiles.yml
new file mode 100644 (file)
index 0000000..ede689b
--- /dev/null
@@ -0,0 +1,14 @@
+development:
+    container_name: appname_development
+    username:
+    api_key: 
+
+test:
+    container_name: appname_test
+    username: 
+    api_key: 
+
+production:
+    container_name: appname_production
+    username: 
+    api_key: 
diff --git a/vendor/plugins/attachment_fu/.gitignore b/vendor/plugins/attachment_fu/.gitignore
new file mode 100644 (file)
index 0000000..1dda17f
--- /dev/null
@@ -0,0 +1,3 @@
+test/amazon_s3.yml
+test/rackspace_cloudfiles.yml
+test/debug.log
index 5aca8cfc45356bbf9bdf369163a8c792dd64e05c..33f5d7e73381058a9d8b86bed9bf8c235496c8b2 100644 (file)
@@ -1,3 +1,14 @@
+* Apr 17 2008 *
+* amazon_s3.yml is now passed through ERB before being passed to AWS::S3 [François Beausoleil]
+
+* Mar 22 2008 *
+* Some tweaks to support Rails 2.0 and Rails 2.1 due to ActiveSupport::Callback changes.  
+  Thanks to http://blog.methodmissing.com/2008/1/19/edge-callback-refactorings-attachment_fu/
+
+* Feb. 26, 2008 *
+* remove breakpoint from test_helper, makes test suite crazy (at least Rails 2+) [Rob Sanheim]
+* make S3 test really optional [Rob Sanheim]
+
 * Nov 27, 2007 *
 * Handle properly ImageScience thumbnails resized from a gif file [Matt Aimonetti]
 * Save thumbnails file size properly when using ImageScience [Matt Aimonetti]
@@ -21,4 +32,4 @@
 * make #current_data public with db_file and s3 backends [ebryn]
 * oops, actually svn add the files for s3 backend. [Jeffrey Hardy]
 * experimental s3 support, egad, no tests.... [Jeffrey Hardy]
-* doh, fix a few bad references to ActsAsAttachment [sixty4bit]
\ No newline at end of file
+* doh, fix a few bad references to ActsAsAttachment [sixty4bit]
diff --git a/vendor/plugins/attachment_fu/LICENSE b/vendor/plugins/attachment_fu/LICENSE
new file mode 100644 (file)
index 0000000..b2d8f02
--- /dev/null
@@ -0,0 +1,20 @@
+Copyright (c) 2009 rick olson
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
index 8db7ba2e76c228452198429d83e3a39a469f7609..baa78c20267917cedcf9c3152d6c172aa2113b90 100644 (file)
@@ -9,12 +9,13 @@ attachment_fu functionality
 
 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.
 
-There are three storage options for files uploaded through attachment_fu:
+There are four storage options for files uploaded through attachment_fu:
   File system
   Database file
   Amazon S3
+  Rackspace (Mosso) Cloud Files
 
-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.
+Each method of storage many options associated with it that will be covered in the following section.  Something to note, however, is that the Amazon S3 storage requires you to modify config/amazon_s3.yml, the Rackspace Cloud Files storage requires you to modify config/rackspace_cloudfiles.yml, and the Database file storage requires an extra table.
 
 
 attachment_fu models
@@ -41,13 +42,18 @@ has_attachment(options = {})
                       # This option need only be included if you want thumbnailing.
     :thumbnail_class  # Set which model class to use for thumbnails.
                       # This current attachment class is used by default.
-    :path_prefix      # path to store the uploaded files.
-                      # Uses public/#{table_name} by default for the filesystem, and just #{table_name} for the S3 backend.  
+    :path_prefix      # Path to store the uploaded files in.
+                      # Uses public/#{table_name} by default for the filesystem, and just #{table_name} for the S3 and Cloud Files backend.  
                       # Setting this sets the :storage to :file_system.
+    :partition        # Whether to partiton files in directories like /0000/0001/image.jpg. Default is true. Only applicable to the :file_system backend.
     :storage          # Specifies the storage system to use..
-                      # Defaults to :db_file.  Options are :file_system, :db_file, and :s3.
+                      # Defaults to :db_file.  Options are :file_system, :db_file, :s3, and :cloud_files.
+    :cloudfront       # If using S3 for storage, this option allows for serving the files via Amazon CloudFront.
+                      # Defaults to false.
     :processor        # Sets the image processor to use for resizing of the attached image.
                       # Options include ImageScience, Rmagick, and MiniMagick.  Default is whatever is installed.
+    :uuid_primary_key # If your model's primary key is a 128-bit UUID in hexadecimal format, then set this to true.
+    :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.
     
 
   Examples:
@@ -60,10 +66,12 @@ has_attachment(options = {})
     has_attachment :thumbnails => { :thumb => [50, 50], :geometry => 'x50' }
     has_attachment :storage => :file_system, :path_prefix => 'public/files'
     has_attachment :storage => :file_system, :path_prefix => 'public/files', 
-                   :content_type => :image, :resize_to => [50,50]
+                   :content_type => :image, :resize_to => [50,50], :partition => false
     has_attachment :storage => :file_system, :path_prefix => 'public/files',
                    :thumbnails => { :thumb => [50, 50], :geometry => 'x50' }
     has_attachment :storage => :s3
+    has_attachment :store => :s3, :cloudfront => true
+    has_attachment :storage => :cloud_files
 
 validates_as_attachment
   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.
@@ -119,7 +127,7 @@ There are two parts of the upload form that differ from typical usage.
     Example:
       <%= form.file_field :uploaded_data %>
 
-Displaying uploaded images is made easy by the public_filename method of the ActiveRecord attachment objects using file system and s3 storage.
+Displaying uploaded images is made easy by the public_filename method of the ActiveRecord attachment objects using file system, s3, and Cloud Files storage.
 
 public_filename(thumbnail = nil)
   Returns the public path to the file.  If a thumbnail prefix is specified it will return the public file path to the corresponding thumbnail.
@@ -160,3 +168,26 @@ Example in controller:
       render :action => :new
     end
   end
+
+attachement_fu scripting
+====================================
+
+You may wish to import a large number of images or attachments. 
+The following example shows how to upload a file from a script. 
+
+#!/usr/bin/env ./script/runner
+
+# required to use ActionController::TestUploadedFile 
+require 'action_controller'
+require 'action_controller/test_process.rb'
+
+path = "./public/images/x.jpg"
+
+# mimetype is a string like "image/jpeg". One way to get the mimetype for a given file on a UNIX system
+# mimetype = `file -ib #{path}`.gsub(/\n/,"")
+
+mimetype = "image/jpeg"
+
+# This will "upload" the file at path and create the new model.
+@attachable = AttachmentMetadataModel.new(:uploaded_data => ActionController::TestUploadedFile.new(path, mimetype))
+@attachable.save
index 81cb807f918e855d574a74c7778dbfb0e75f862a..5c585e78eb1aa3285662717e1dd76ba5e43a8bbc 100644 (file)
@@ -2,13 +2,16 @@ development:
   bucket_name: appname_development
   access_key_id: 
   secret_access_key: 
+  distribution_domain: XXXX.cloudfront.net
 
 test:
   bucket_name: appname_test
   access_key_id: 
   secret_access_key: 
+  distribution_domain: XXXX.cloudfront.net
 
 production:
   bucket_name: appname
   access_key_id: 
   secret_access_key: 
+  distribution_domain: XXXX.cloudfront.net
index 0239e56b370ced1034360721e8f9a67c17a93ad4..dadcb07891ce1bf0c24daeed0aaaaceffad939b7 100644 (file)
@@ -11,4 +11,6 @@ end
 require 'geometry'
 ActiveRecord::Base.send(:extend, Technoweenie::AttachmentFu::ActMethods)
 Technoweenie::AttachmentFu.tempfile_path = ATTACHMENT_FU_TEMPFILE_PATH if Object.const_defined?(:ATTACHMENT_FU_TEMPFILE_PATH)
-FileUtils.mkdir_p Technoweenie::AttachmentFu.tempfile_path
\ No newline at end of file
+FileUtils.mkdir_p Technoweenie::AttachmentFu.tempfile_path
+
+$:.unshift(File.dirname(__FILE__) + '/vendor')
index 29381641d850527ccc93c25ef3a454296a2a8a35..163c7db37ea682f18edca5f9ea988e2cf2c34690 100644 (file)
@@ -2,4 +2,6 @@ require 'fileutils'
 
 s3_config = File.dirname(__FILE__) + '/../../../config/amazon_s3.yml'
 FileUtils.cp File.dirname(__FILE__) + '/amazon_s3.yml.tpl', s3_config unless File.exist?(s3_config)
+cloudfiles_config = File.dirname(__FILE__) + '/../../../config/rackspace_cloudfiles.yml'
+FileUtils.cp File.dirname(__FILE__) + '/rackspace_cloudfiles.yml.tpl', cloudfiles_config unless File.exist?(cloudfiles_config)
 puts IO.read(File.join(File.dirname(__FILE__), 'README'))
\ No newline at end of file
index 2d6e38166fc8624baa3522c35b056b9f920b0821..73a7ca221ea496472441066f01f1cea71e908878 100644 (file)
@@ -25,7 +25,7 @@ class Geometry
   end
 
   # Construct an object from a geometry string
-  RE = /\A(\d*)(?:x(\d+))?([-+]\d+)?([-+]\d+)?([%!<>@]?)\Z/
+  RE = /\A(\d*)(?:x(\d+)?)?([-+]\d+)?([-+]\d+)?([%!<>@]?)\Z/
 
   def self.from_s(str)
     raise(ArgumentError, "no geometry string specified") unless str
@@ -76,7 +76,7 @@ class Geometry
         new_height = orig_height if @flag && orig_height.send(@flag, new_height)
     end
 
-    [new_width, new_height].collect! { |v| v.round }
+    [new_width, new_height].collect! { |v| [v.round, 1].max }
   end
 end
 
@@ -90,4 +90,4 @@ class Array
     geometry = Geometry.from_s(geometry) if geometry.is_a?(String)
     geometry.new_dimensions_for first, last
   end
-end
\ No newline at end of file
+end
index 013e225fa929b9b0a2b20878dbf7193fbf459139..e282825ba62d0df830d8ec1126a1ba4f49af0d72 100644 (file)
@@ -1,8 +1,38 @@
 module Technoweenie # :nodoc:
   module AttachmentFu # :nodoc:
-    @@default_processors = %w(ImageScience Rmagick MiniMagick)
+    @@default_processors = %w(ImageScience Rmagick MiniMagick Gd2 CoreImage)
     @@tempfile_path      = File.join(RAILS_ROOT, 'tmp', 'attachment_fu')
-    @@content_types      = ['image/jpeg', 'image/pjpeg', 'image/gif', 'image/png', 'image/x-png', 'image/jpg']
+    @@content_types      = [
+      'image/jpeg',
+      'image/pjpeg',
+      'image/jpg',
+      'image/gif',
+      'image/png',
+      'image/x-png',
+      'image/jpg',
+      'image/x-ms-bmp',
+      'image/bmp',
+      'image/x-bmp',
+      'image/x-bitmap',
+      'image/x-xbitmap',
+      'image/x-win-bitmap',
+      'image/x-windows-bmp',
+      'image/ms-bmp',
+      'application/bmp',
+      'application/x-bmp',
+      'application/x-win-bitmap',
+      'application/preview',
+      'image/jp_',
+      'application/jpg',
+      'application/x-jpg',
+      'image/pipeg',
+      'image/vnd.swiftview-jpeg',
+      'image/x-xbitmap',
+      'application/png',
+      'application/x-png',
+      'image/gi_',
+      'image/x-citrix-pjpeg'
+    ]
     mattr_reader :content_types, :tempfile_path, :default_processors
     mattr_writer :tempfile_path
 
@@ -10,7 +40,7 @@ module Technoweenie # :nodoc:
     class AttachmentError < StandardError; end
 
     module ActMethods
-      # Options: 
+      # Options:
       # *  <tt>:content_type</tt> - Allowed content types.  Allows all by default.  Use :image to allow all standard image types.
       # *  <tt>:min_size</tt> - Minimum size allowed.  1 byte is the default.
       # *  <tt>:max_size</tt> - Maximum size allowed.  1.megabyte is the default.
@@ -20,7 +50,15 @@ module Technoweenie # :nodoc:
       # *  <tt>:thumbnail_class</tt> - Set what class to use for thumbnails.  This attachment class is used by default.
       # *  <tt>:path_prefix</tt> - path to store the uploaded files.  Uses public/#{table_name} by default for the filesystem, and just #{table_name}
       #      for the S3 backend.  Setting this sets the :storage to :file_system.
+
       # *  <tt>:storage</tt> - Use :file_system to specify the attachment data is stored with the file system.  Defaults to :db_system.
+      # *  <tt>:cloundfront</tt> - Set to true if you are using S3 storage and want to serve the files through CloudFront.  You will need to
+      #      set a distribution domain in the amazon_s3.yml config file. Defaults to false
+      # *  <tt>:bucket_key</tt> - Use this to specify a different bucket key other than :bucket_name in the amazon_s3.yml file.  This allows you to use
+      #      different buckets for different models. An example setting would be :image_bucket and the you would need to define the name of the corresponding
+      #      bucket in the amazon_s3.yml file.
+
+      # *  <tt>:keep_profile</tt> By default image EXIF data will be stripped to minimize image size. For small thumbnails this proivides important savings. Picture quality is not affected. Set to false if you want to keep the image profile as is. ImageScience will allways keep EXIF data.
       #
       # Examples:
       #   has_attachment :max_size => 1.kilobyte
@@ -31,7 +69,7 @@ module Technoweenie # :nodoc:
       #   has_attachment :content_type => ['application/pdf', :image], :resize_to => 'x50'
       #   has_attachment :thumbnails => { :thumb => [50, 50], :geometry => 'x50' }
       #   has_attachment :storage => :file_system, :path_prefix => 'public/files'
-      #   has_attachment :storage => :file_system, :path_prefix => 'public/files', 
+      #   has_attachment :storage => :file_system, :path_prefix => 'public/files',
       #     :content_type => :image, :resize_to => [50,50]
       #   has_attachment :storage => :file_system, :path_prefix => 'public/files',
       #     :thumbnails => { :thumb => [50, 50], :geometry => 'x50' }
@@ -44,62 +82,84 @@ module Technoweenie # :nodoc:
         options[:thumbnails]       ||= {}
         options[:thumbnail_class]  ||= self
         options[:s3_access]        ||= :public_read
+        options[:cloudfront]       ||= false
         options[:content_type] = [options[:content_type]].flatten.collect! { |t| t == :image ? Technoweenie::AttachmentFu.content_types : t }.flatten unless options[:content_type].nil?
-        
+
         unless options[:thumbnails].is_a?(Hash)
           raise ArgumentError, ":thumbnails option should be a hash: e.g. :thumbnails => { :foo => '50x50' }"
         end
-        
+
+        extend ClassMethods unless (class << self; included_modules; end).include?(ClassMethods)
+        include InstanceMethods unless included_modules.include?(InstanceMethods)
+
+        parent_options = attachment_options || {}
         # doing these shenanigans so that #attachment_options is available to processors and backends
-        class_inheritable_accessor :attachment_options
         self.attachment_options = options
 
-        # only need to define these once on a class
-        unless included_modules.include?(InstanceMethods)
-          attr_accessor :thumbnail_resize_options
+        attr_accessor :thumbnail_resize_options
 
-          attachment_options[:storage]     ||= (attachment_options[:file_system_path] || attachment_options[:path_prefix]) ? :file_system : :db_file
-          attachment_options[:path_prefix] ||= attachment_options[:file_system_path]
-          if attachment_options[:path_prefix].nil?
-            attachment_options[:path_prefix] = attachment_options[:storage] == :s3 ? table_name : File.join("public", table_name)
+        attachment_options[:storage]     ||= (attachment_options[:file_system_path] || attachment_options[:path_prefix]) ? :file_system : :db_file
+        attachment_options[:storage]     ||= parent_options[:storage]
+        attachment_options[:path_prefix] ||= attachment_options[:file_system_path]
+        if attachment_options[:path_prefix].nil?
+          attachment_options[:path_prefix] = case attachment_options[:storage]
+            when :s3 then table_name
+            when :cloud_files then table_name
+            else File.join("public", table_name)
           end
-          attachment_options[:path_prefix]   = attachment_options[:path_prefix][1..-1] if options[:path_prefix].first == '/'
+        end
+        attachment_options[:path_prefix]   = attachment_options[:path_prefix][1..-1] if options[:path_prefix].first == '/'
 
-          with_options :foreign_key => 'parent_id' do |m|
-            m.has_many   :thumbnails, :class_name => attachment_options[:thumbnail_class].to_s
-            m.belongs_to :parent, :class_name => base_class.to_s
+        association_options = { :foreign_key => 'parent_id' }
+        if attachment_options[:association_options]
+          association_options.merge!(attachment_options[:association_options])
+        end
+        with_options(association_options) do |m|
+          m.has_many   :thumbnails, :class_name => "::#{attachment_options[:thumbnail_class]}"
+          m.belongs_to :parent, :class_name => "::#{base_class}" unless options[:thumbnails].empty?
+        end
+
+        storage_mod = Technoweenie::AttachmentFu::Backends.const_get("#{options[:storage].to_s.classify}Backend")
+        include storage_mod unless included_modules.include?(storage_mod)
+
+        case attachment_options[:processor]
+        when :none, nil
+          processors = Technoweenie::AttachmentFu.default_processors.dup
+          begin
+            if processors.any?
+              attachment_options[:processor] = processors.first
+              processor_mod = Technoweenie::AttachmentFu::Processors.const_get("#{attachment_options[:processor].to_s.classify}Processor")
+              include processor_mod unless included_modules.include?(processor_mod)
+            end
+          rescue Object, Exception
+            raise unless load_related_exception?($!)
+
+            processors.shift
+            retry
           end
-          before_destroy :destroy_thumbnails
-
-          before_validation :set_size_from_temp_path
-          after_save :after_process_attachment
-          after_destroy :destroy_file
-          extend  ClassMethods
-          include InstanceMethods
-          include Technoweenie::AttachmentFu::Backends.const_get("#{options[:storage].to_s.classify}Backend")
-          case attachment_options[:processor]
-            when :none
-            when nil
-              processors = Technoweenie::AttachmentFu.default_processors.dup
-              begin
-                if processors.any?
-                  attachment_options[:processor] = "#{processors.first}Processor"
-                  include Technoweenie::AttachmentFu::Processors.const_get(attachment_options[:processor])
-                end
-              rescue LoadError, MissingSourceFile
-                processors.shift
-                retry
-              end
-            else
-              begin
-                include Technoweenie::AttachmentFu::Processors.const_get("#{options[:processor].to_s.classify}Processor")
-              rescue LoadError, MissingSourceFile
-                puts "Problems loading #{options[:processor]}Processor: #{$!}"
-              end
+        else
+          begin
+            processor_mod = Technoweenie::AttachmentFu::Processors.const_get("#{attachment_options[:processor].to_s.classify}Processor")
+            include processor_mod unless included_modules.include?(processor_mod)
+          rescue Object, Exception
+            raise unless load_related_exception?($!)
+
+            puts "Problems loading #{options[:processor]}Processor: #{$!}"
           end
-          after_validation :process_attachment
+        end unless parent_options[:processor] # Don't let child override processor
+      end
+
+      def load_related_exception?(e) #:nodoc: implementation specific
+        case
+        when e.kind_of?(LoadError), e.kind_of?(MissingSourceFile), $!.class.name == "CompilationError"
+          # We can't rescue CompilationError directly, as it is part of the RubyInline library.
+          # We must instead rescue RuntimeError, and check the class' name.
+          true
+        else
+          false
         end
       end
+      private :load_related_exception?
     end
 
     module ClassMethods
@@ -116,41 +176,56 @@ module Technoweenie # :nodoc:
         content_types.include?(content_type)
       end
 
-      # Callback after an image has been resized.
-      #
-      #   class Foo < ActiveRecord::Base
-      #     acts_as_attachment
-      #     after_resize do |record, img| 
-      #       record.aspect_ratio = img.columns.to_f / img.rows.to_f
-      #     end
-      #   end
-      def after_resize(&block)
-        write_inheritable_array(:after_resize, [block])
+      def self.extended(base)
+        base.class_inheritable_accessor :attachment_options
+        base.before_destroy :destroy_thumbnails
+        base.before_validation :set_size_from_temp_path
+        base.after_save :after_process_attachment
+        base.after_destroy :destroy_file
+        base.after_validation :process_attachment
+        if defined?(::ActiveSupport::Callbacks)
+          base.define_callbacks :after_resize, :after_attachment_saved, :before_thumbnail_saved
+        end
       end
 
-      # Callback after an attachment has been saved either to the file system or the DB.
-      # Only called if the file has been changed, not necessarily if the record is updated.
-      #
-      #   class Foo < ActiveRecord::Base
-      #     acts_as_attachment
-      #     after_attachment_saved do |record|
-      #       ...
-      #     end
-      #   end
-      def after_attachment_saved(&block)
-        write_inheritable_array(:after_attachment_saved, [block])
-      end
+      unless defined?(::ActiveSupport::Callbacks)
+        # Callback after an image has been resized.
+        #
+        #   class Foo < ActiveRecord::Base
+        #     acts_as_attachment
+        #     after_resize do |record, img|
+        #       record.aspect_ratio = img.columns.to_f / img.rows.to_f
+        #     end
+        #   end
+        def after_resize(&block)
+          write_inheritable_array(:after_resize, [block])
+        end
 
-      # Callback before a thumbnail is saved.  Use this to pass any necessary extra attributes that may be required.
-      #
-      #   class Foo < ActiveRecord::Base
-      #     acts_as_attachment
-      #     before_thumbnail_saved do |record, thumbnail|
-      #       ...
-      #     end
-      #   end
-      def before_thumbnail_saved(&block)
-        write_inheritable_array(:before_thumbnail_saved, [block])
+        # Callback after an attachment has been saved either to the file system or the DB.
+        # Only called if the file has been changed, not necessarily if the record is updated.
+        #
+        #   class Foo < ActiveRecord::Base
+        #     acts_as_attachment
+        #     after_attachment_saved do |record|
+        #       ...
+        #     end
+        #   end
+        def after_attachment_saved(&block)
+          write_inheritable_array(:after_attachment_saved, [block])
+        end
+
+        # Callback before a thumbnail is saved.  Use this to pass any necessary extra attributes that may be required.
+        #
+        #   class Foo < ActiveRecord::Base
+        #     acts_as_attachment
+        #     before_thumbnail_saved do |thumbnail|
+        #       record = thumbnail.parent
+        #       ...
+        #     end
+        #   end
+        def before_thumbnail_saved(&block)
+          write_inheritable_array(:before_thumbnail_saved, [block])
+        end
       end
 
       # Get the thumbnail class, which is the current attachment class by default.
@@ -167,7 +242,7 @@ module Technoweenie # :nodoc:
           FileUtils.cp file, tmp.path
         end
       end
-      
+
       # Writes the given data to a new tempfile, returning the closed tempfile.
       def write_to_temp_file(data, temp_base_name)
         returning Tempfile.new(temp_base_name, Technoweenie::AttachmentFu.tempfile_path) do |tmp|
@@ -179,11 +254,15 @@ module Technoweenie # :nodoc:
     end
 
     module InstanceMethods
+      def self.included(base)
+        base.define_callbacks *[:after_resize, :after_attachment_saved, :before_thumbnail_saved] if base.respond_to?(:define_callbacks)
+      end
+
       # Checks whether the attachment's content type is an image content type
       def image?
         self.class.image?(content_type)
       end
-      
+
       # Returns true/false if an attachment is thumbnailable.  A thumbnailable attachment has an image content type and the parent_id attribute.
       def thumbnailable?
         image? && respond_to?(:parent_id) && parent_id.nil?
@@ -202,7 +281,7 @@ module Technoweenie # :nodoc:
           ext = s; ''
         end
         # ImageScience doesn't create gif thumbnails, only pngs
-        ext.sub!(/gif$/, 'png') if attachment_options[:processor] == "ImageScienceProcessor"
+        ext.sub!(/gif$/, 'png') if attachment_options[:processor] == "ImageScience"
         "#{basename}_#{thumbnail}#{ext}"
       end
 
@@ -210,12 +289,12 @@ module Technoweenie # :nodoc:
       def create_or_update_thumbnail(temp_file, file_name_suffix, *size)
         thumbnailable? || raise(ThumbnailError.new("Can't create a thumbnail if the content type is not an image or there is no parent_id column"))
         returning find_or_initialize_thumbnail(file_name_suffix) do |thumb|
-          thumb.attributes = {
-            :content_type             => content_type, 
-            :filename                 => thumbnail_name_for(file_name_suffix), 
-            :temp_path                => temp_file,
+          thumb.temp_paths.unshift temp_file
+          thumb.send(:'attributes=', {
+            :content_type             => content_type,
+            :filename                 => thumbnail_name_for(file_name_suffix),
             :thumbnail_resize_options => size
-          }
+          }, false)
           callback_with_args :before_thumbnail_saved, thumb
           thumb.save!
         end
@@ -225,7 +304,7 @@ module Technoweenie # :nodoc:
       def content_type=(new_type)
         write_attribute :content_type, new_type.to_s.strip
       end
-      
+
       # Sanitizes a filename.
       def filename=(new_name)
         write_attribute :filename, sanitize_filename(new_name)
@@ -256,14 +335,21 @@ module Technoweenie # :nodoc:
       #
       # TODO: Allow it to work with Merb tempfiles too.
       def uploaded_data=(file_data)
-        return nil if file_data.nil? || file_data.size == 0 
-        self.content_type = file_data.content_type
-        self.filename     = file_data.original_filename if respond_to?(:filename)
+        if file_data.respond_to?(:content_type)
+          return nil if file_data.size == 0
+          self.content_type = file_data.content_type
+          self.filename     = file_data.original_filename if respond_to?(:filename)
+        else
+          return nil if file_data.blank? || file_data['size'] == 0
+          self.content_type = file_data['content_type']
+          self.filename =  file_data['filename']
+          file_data = file_data['tempfile']
+        end
         if file_data.is_a?(StringIO)
           file_data.rewind
-          self.temp_data = file_data.read
+          set_temp_data file_data.read
         else
-          self.temp_path = file_data.path
+          self.temp_paths.unshift file_data
         end
       end
 
@@ -275,40 +361,33 @@ module Technoweenie # :nodoc:
         p = temp_paths.first
         p.respond_to?(:path) ? p.path : p.to_s
       end
-      
+
       # Gets an array of the currently used temp paths.  Defaults to a copy of #full_filename.
       def temp_paths
-        @temp_paths ||= (new_record? || !File.exist?(full_filename)) ? [] : [copy_to_temp_file(full_filename)]
-      end
-      
-      # Adds a new temp_path to the array.  This should take a string or a Tempfile.  This class makes no 
-      # attempt to remove the files, so Tempfiles should be used.  Tempfiles remove themselves when they go out of scope.
-      # You can also use string paths for temporary files, such as those used for uploaded files in a web server.
-      def temp_path=(value)
-        temp_paths.unshift value
-        temp_path
+        @temp_paths ||= (new_record? || !respond_to?(:full_filename) || !File.exist?(full_filename) ?
+          [] : [copy_to_temp_file(full_filename)])
       end
 
       # Gets the data from the latest temp file.  This will read the file into memory.
       def temp_data
         save_attachment? ? File.read(temp_path) : nil
       end
-      
+
       # Writes the given data to a Tempfile and adds it to the collection of temp files.
-      def temp_data=(data)
-        self.temp_path = write_to_temp_file data unless data.nil?
+      def set_temp_data(data)
+        temp_paths.unshift write_to_temp_file data unless data.nil?
       end
-      
+
       # Copies the given file to a randomly named Tempfile.
       def copy_to_temp_file(file)
         self.class.copy_to_temp_file file, random_tempfile_filename
       end
-      
+
       # Writes the given file to a randomly named Tempfile.
       def write_to_temp_file(data)
         self.class.write_to_temp_file data, random_tempfile_filename
       end
-      
+
       # Stub for creating a temp file from the attachment data.  This should be defined in the backend module.
       def create_temp_file() end
 
@@ -323,19 +402,20 @@ module Technoweenie # :nodoc:
       end
 
       protected
-        # Generates a unique filename for a Tempfile. 
+        # Generates a unique filename for a Tempfile.
         def random_tempfile_filename
           "#{rand Time.now.to_i}#{filename || 'attachment'}"
         end
 
         def sanitize_filename(filename)
+          return unless filename
           returning filename.strip do |name|
             # NOTE: File.basename doesn't work right with Windows paths on Unix
             # get only the filename, not the whole path
             name.gsub! /^.*(\\|\/)/, ''
-            
+
             # Finally, replace all non alphanumeric, underscore or periods with underscore
-            name.gsub! /[^\w\.\-]/, '_'
+            name.gsub! /[^A-Za-z0-9\.\-]/, '_'
           end
         end
 
@@ -348,7 +428,11 @@ module Technoweenie # :nodoc:
         def attachment_attributes_valid?
           [:size, :content_type].each do |attr_name|
             enum = attachment_options[attr_name]
-            errors.add attr_name, ActiveRecord::Errors.default_error_messages[:inclusion] unless enum.nil? || enum.include?(send(attr_name))
+            if Object.const_defined?(:I18n) # Rails >= 2.2
+              errors.add attr_name, I18n.translate("activerecord.errors.messages.inclusion", attr_name => enum) unless enum.nil? || enum.include?(send(attr_name))
+            else
+              errors.add attr_name, ActiveRecord::Errors.default_error_messages[:inclusion] unless enum.nil? || enum.include?(send(attr_name))
+            end
           end
         end
 
@@ -383,24 +467,44 @@ module Technoweenie # :nodoc:
           if (!respond_to?(:parent_id) || parent_id.nil?) && attachment_options[:resize_to] # parent image
             resize_image(img, attachment_options[:resize_to])
           elsif thumbnail_resize_options # thumbnail
-            resize_image(img, thumbnail_resize_options) 
+            resize_image(img, thumbnail_resize_options)
           end
         end
 
         # Yanked from ActiveRecord::Callbacks, modified so I can pass args to the callbacks besides self.
         # Only accept blocks, however
-        def callback_with_args(method, arg = self)
-          notify(method)
+        if ActiveSupport.const_defined?(:Callbacks)
+          # Rails 2.1 and beyond!
+          def callback_with_args(method, arg = self)
+            notify(method)
+
+            result = run_callbacks(method, { :object => arg }) { |result, object| result == false }
 
-          result = nil
-          callbacks_for(method).each do |callback|
-            result = callback.call(self, arg)
-            return false if result == false
+            if result != false && respond_to_without_attributes?(method)
+              result = send(method)
+            end
+
+            result
           end
 
-          return result
+          def run_callbacks(kind, options = {}, &block)
+            options.reverse_merge!( :object => self )
+            self.class.send("#{kind}_callback_chain").run(options[:object], options, &block)
+          end
+        else
+          # Rails 2.0
+          def callback_with_args(method, arg = self)
+            notify(method)
+
+            result = nil
+            callbacks_for(method).each do |callback|
+              result = callback.call(self, arg)
+              return false if result == false
+            end
+            result
+          end
         end
-        
+
         # Removes the thumbnails for the attachment, if it has any
         def destroy_thumbnails
           self.thumbnails.each { |thumbnail| thumbnail.destroy } if thumbnailable?
diff --git a/vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu/backends/cloud_file_backend.rb b/vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu/backends/cloud_file_backend.rb
new file mode 100644 (file)
index 0000000..214ab27
--- /dev/null
@@ -0,0 +1,211 @@
+module Technoweenie # :nodoc:
+  module AttachmentFu # :nodoc:
+    module Backends
+      # = CloudFiles Storage Backend
+      #
+      # Enables use of {Rackspace Cloud Files}[http://www.mosso.com/cloudfiles.jsp] as a storage mechanism
+      #
+      # Based heavily on the Amazon S3 backend.
+      #
+      # == Requirements
+      #
+      # Requires the {Cloud Files Gem}[http://www.mosso.com/cloudfiles.jsp] by Rackspace 
+      #
+      # == Configuration
+      #
+      # Configuration is done via <tt>RAILS_ROOT/config/rackspace_cloudfiles.yml</tt> and is loaded according to the <tt>RAILS_ENV</tt>.
+      # The minimum connection options that you must specify are a container name, your Mosso login name and your Mosso API key.
+      # You can sign up for Cloud Files and get access keys by visiting https://www.mosso.com/buy.htm 
+      #
+      # Example configuration (RAILS_ROOT/config/rackspace_cloudfiles.yml)
+      #
+      #   development:
+      #     container_name: appname_development
+      #     username: <your key>
+      #     api_key: <your key>
+      #
+      #   test:
+      #     container_name: appname_test
+      #     username: <your key>
+      #     api_key: <your key>
+      #
+      #   production:
+      #     container_name: appname
+      #     username: <your key>
+      #     apik_key: <your key>
+      #
+      # You can change the location of the config path by passing a full path to the :cloudfiles_config_path option.
+      #
+      #   has_attachment :storage => :cloud_files, :cloudfiles_config_path => (RAILS_ROOT + '/config/mosso.yml')
+      #
+      # === Required configuration parameters
+      #
+      # * <tt>:username</tt> - The username for your Rackspace Cloud (Mosso) account. Provided by Rackspace.
+      # * <tt>:secret_access_key</tt> - The api key for your Rackspace Cloud account. Provided by Rackspace.
+      # * <tt>:container_name</tt> - The name of a container in your Cloud Files account.
+      #
+      # If any of these required arguments is missing, a AuthenticationException will be raised from CloudFiles::Connection.
+      #
+      # == Usage
+      #
+      # To specify Cloud Files as the storage mechanism for a model, set the acts_as_attachment <tt>:storage</tt> option to <tt>:cloud_files/tt>.
+      #
+      #   class Photo < ActiveRecord::Base
+      #     has_attachment :storage => :cloud_files
+      #   end
+      #
+      # === Customizing the path
+      #
+      # By default, files are prefixed using a pseudo hierarchy in the form of <tt>:table_name/:id</tt>, which results
+      # in Cloud Files object names (and urls) that look like: http://:server/:container_name/:table_name/:id/:filename with :table_name
+      # representing the customizable portion of the path. You can customize this prefix using the <tt>:path_prefix</tt>
+      # option:
+      #
+      #   class Photo < ActiveRecord::Base
+      #     has_attachment :storage => :cloud_files, :path_prefix => 'my/custom/path'
+      #   end
+      #
+      # Which would result in public URLs like <tt>http(s)://:server/:container_name/my/custom/path/:id/:filename.</tt>
+      #
+      # === Permissions
+      #
+      # File permisisons are determined by the permissions of the container.  At present, the options are public (and distributed
+      # by the Limelight CDN), and private (only available to your login)
+      #
+      # === Other options
+      #
+      # Of course, all the usual configuration options apply, such as content_type and thumbnails:
+      #
+      #   class Photo < ActiveRecord::Base
+      #     has_attachment :storage => :cloud_files, :content_type => ['application/pdf', :image], :resize_to => 'x50'
+      #     has_attachment :storage => :cloud_files, :thumbnails => { :thumb => [50, 50], :geometry => 'x50' }
+      #   end
+      #
+      # === Accessing Cloud Files URLs
+      #
+      # You can get an object's public URL using the cloudfiles_url accessor. For example, assuming that for your postcard app
+      # you had a container name like 'postcard_world_development', and an attachment model called Photo:
+      #
+      #   @postcard.cloudfiles_url # => http://cdn.cloudfiles.mosso.com/c45182/uploaded_files/20/london.jpg
+      #
+      # The resulting url is in the form: http://:server/:container_name/:table_name/:id/:file.
+      # The optional thumbnail argument will output the thumbnail's filename (if any).
+      #
+      # Additionally, you can get an object's base path relative to the container root using
+      # <tt>base_path</tt>:
+      #
+      #   @photo.file_base_path # => uploaded_files/20
+      #
+      # And the full path (including the filename) using <tt>full_filename</tt>:
+      #
+      #   @photo.full_filename # => uploaded_files/20/london.jpg
+      #
+      # Niether <tt>base_path</tt> or <tt>full_filename</tt> include the container name as part of the path.
+      # You can retrieve the container name using the <tt>container_name</tt> method.
+      module CloudFileBackend
+        class RequiredLibraryNotFoundError < StandardError; end
+        class ConfigFileNotFoundError < StandardError; end
+
+        def self.included(base) #:nodoc:
+          mattr_reader :container_name, :cloudfiles_config
+
+          begin
+            require 'cloudfiles'
+          rescue LoadError
+            raise RequiredLibraryNotFoundError.new('CloudFiles could not be loaded')
+          end
+
+          begin
+            @@cloudfiles_config_path = base.attachment_options[:cloudfiles_config_path] || (RAILS_ROOT + '/config/rackspace_cloudfiles.yml')
+            @@cloudfiles_config = @@cloudfiles_config = YAML.load(ERB.new(File.read(@@cloudfiles_config_path)).result)[RAILS_ENV].symbolize_keys
+          rescue
+            #raise ConfigFileNotFoundError.new('File %s not found' % @@cloudfiles_config_path)
+          end
+
+          @@container_name = @@cloudfiles_config[:container_name]
+          @@cf = CloudFiles::Connection.new(@@cloudfiles_config[:username], @@cloudfiles_config[:api_key])
+          @@container = @@cf.container(@@container_name)
+          
+          base.before_update :rename_file
+        end
+
+        # Overwrites the base filename writer in order to store the old filename
+        def filename=(value)
+          @old_filename = filename unless filename.nil? || @old_filename
+          write_attribute :filename, sanitize_filename(value)
+        end
+
+        # The attachment ID used in the full path of a file
+        def attachment_path_id
+          ((respond_to?(:parent_id) && parent_id) || id).to_s
+        end
+
+        # The pseudo hierarchy containing the file relative to the container name
+        # Example: <tt>:table_name/:id</tt>
+        def base_path
+          File.join(attachment_options[:path_prefix], attachment_path_id)
+        end
+
+        # The full path to the file relative to the container name
+        # Example: <tt>:table_name/:id/:filename</tt>
+        def full_filename(thumbnail = nil)
+          File.join(base_path, thumbnail_name_for(thumbnail))
+        end
+
+        # All public objects are accessible via a GET request to the Cloud Files servers. You can generate a
+        # url for an object using the cloudfiles_url method.
+        #
+        #   @photo.cloudfiles_url
+        #
+        # The resulting url is in the CDN URL for the object
+        #
+        # The optional thumbnail argument will output the thumbnail's filename (if any).
+        #
+        # If you are trying to get the URL for a nonpublic container, nil will be returned.
+        def cloudfiles_url(thumbnail = nil)
+          if @@container.public?
+            File.join(@@container.cdn_url, full_filename(thumbnail))
+          else
+            nil
+          end
+        end
+        alias :public_filename :cloudfiles_url
+
+        def create_temp_file
+          write_to_temp_file current_data
+        end
+
+        def current_data
+          @@container.get_object(full_filename).data
+        end
+
+        protected
+          # Called in the after_destroy callback
+          def destroy_file
+            @@container.delete_object(full_filename)
+          end
+
+          def rename_file
+            # Cloud Files doesn't rename right now, so we'll just nuke.
+            return unless @old_filename && @old_filename != filename
+
+            old_full_filename = File.join(base_path, @old_filename)
+            @@container.delete_object(old_full_filename)
+
+            @old_filename = nil
+            true
+          end
+
+          def save_to_storage
+            if save_attachment?
+              @object = @@container.create_object(full_filename)
+              @object.write((temp_path ? File.open(temp_path) : temp_data))
+            end
+
+            @old_filename = nil
+            true
+          end
+      end
+    end
+  end
+end
index 464b9c778060088151d073b3abe487abf12d0608..352cd3114dd7b43bcf5e00429fcb017fdae6f5a7 100644 (file)
@@ -1,4 +1,6 @@
-require 'ftools'
+require 'fileutils'
+require 'digest/sha2'
+
 module Technoweenie # :nodoc:
   module AttachmentFu # :nodoc:
     module Backends
@@ -28,13 +30,40 @@ module Technoweenie # :nodoc:
       
         # The attachment ID used in the full path of a file
         def attachment_path_id
-          ((respond_to?(:parent_id) && parent_id) || id).to_i
+          ((respond_to?(:parent_id) && parent_id) || id) || 0
         end
       
-        # overrwrite this to do your own app-specific partitioning. 
-        # you can thank Jamis Buck for this: http://www.37signals.com/svn/archives2/id_partitioning.php
+        # Partitions the given path into an array of path components.
+        #
+        # For example, given an <tt>*args</tt> of ["foo", "bar"], it will return
+        # <tt>["0000", "0001", "foo", "bar"]</tt> (assuming that that id returns 1).
+        #
+        # If the id is not an integer, then path partitioning will be performed by
+        # hashing the string value of the id with SHA-512, and splitting the result
+        # into 4 components. If the id a 128-bit UUID (as set by :uuid_primary_key => true)
+        # then it will be split into 2 components.
+        # 
+        # To turn this off entirely, set :partition => false.
         def partitioned_path(*args)
-          ("%08d" % attachment_path_id).scan(/..../) + args
+          if respond_to?(:attachment_options) && attachment_options[:partition] == false 
+            args
+          elsif attachment_options[:uuid_primary_key]
+            # Primary key is a 128-bit UUID in hex format. Split it into 2 components.
+            path_id = attachment_path_id.to_s
+            component1 = path_id[0..15] || "-"
+            component2 = path_id[16..-1] || "-"
+            [component1, component2] + args
+          else
+            path_id = attachment_path_id
+            if path_id.is_a?(Integer)
+              # Primary key is an integer. Split it after padding it with 0.
+              ("%08d" % path_id).scan(/..../) + args
+            else
+              # Primary key is a String. Hash it, then split it into 4 components.
+              hash = Digest::SHA512.hexdigest(path_id.to_s)
+              [hash[0..31], hash[32..63], hash[64..95], hash[96..127]] + args
+            end
+          end
         end
       
         # Gets the public path to the file
@@ -81,8 +110,8 @@ module Technoweenie # :nodoc:
             if save_attachment?
               # TODO: This overwrites the file if it exists, maybe have an allow_overwrite option?
               FileUtils.mkdir_p(File.dirname(full_filename))
-              File.cp(temp_path, full_filename)
-              File.chmod(attachment_options[:chmod] || 0644, full_filename)
+              FileUtils.cp(temp_path, full_filename)
+              FileUtils.chmod(attachment_options[:chmod] || 0644, full_filename)
             end
             @old_filename = nil
             true
@@ -94,4 +123,4 @@ module Technoweenie # :nodoc:
       end
     end
   end
-end
\ No newline at end of file
+end
index b81fbde8a4152e195a2b42365087b9c62b04fad5..53b0caf5c6295daebb63557b138e6300572ba77e 100644 (file)
@@ -17,22 +17,28 @@ module Technoweenie # :nodoc:
       # If you don't already have your access keys, all you need to sign up for the S3 service is an account at Amazon.
       # You can sign up for S3 and get access keys by visiting http://aws.amazon.com/s3.
       #
+      # If you wish to use Amazon CloudFront to serve the files, you can also specify a distibution domain for the bucket.
+      # To read more about CloudFront, visit http://aws.amazon.com/cloudfront
+      #
       # Example configuration (RAILS_ROOT/config/amazon_s3.yml)
-      # 
+      #
       #   development:
       #     bucket_name: appname_development
       #     access_key_id: <your key>
       #     secret_access_key: <your key>
-      #   
+      #     distribution_domain: XXXX.cloudfront.net
+      #
       #   test:
       #     bucket_name: appname_test
       #     access_key_id: <your key>
       #     secret_access_key: <your key>
-      #   
+      #     distribution_domain: XXXX.cloudfront.net
+      #
       #   production:
       #     bucket_name: appname
       #     access_key_id: <your key>
       #     secret_access_key: <your key>
+      #     distribution_domain: XXXX.cloudfront.net
       #
       # You can change the location of the config path by passing a full path to the :s3_config_path option.
       #
@@ -59,6 +65,8 @@ module Technoweenie # :nodoc:
       # * <tt>:server</tt> - The server to make requests to. Defaults to <tt>s3.amazonaws.com</tt>.
       # * <tt>:port</tt> - The port to the requests should be made on. Defaults to 80 or 443 if <tt>:use_ssl</tt> is set.
       # * <tt>:use_ssl</tt> - If set to true, <tt>:port</tt> will be implicitly set to 443, unless specified otherwise. Defaults to false.
+      # * <tt>:distribution_domain</tt> - The CloudFront distribution domain for the bucket.  This can either be the assigned
+      #     distribution domain (ie. XXX.cloudfront.net) or a chosen domain using a CNAME. See CloudFront for more details.
       #
       # == Usage
       #
@@ -81,10 +89,43 @@ module Technoweenie # :nodoc:
       #
       # Which would result in URLs like <tt>http(s)://:server/:bucket_name/my/custom/path/:id/:filename.</tt>
       #
+      # === Using different bucket names on different models
+      #
+      # By default the bucket name that the file will be stored to is the one specified by the
+      # <tt>:bucket_name</tt> key in the amazon_s3.yml file.  You can use the <tt>:bucket_key</tt> option
+      # to overide this behavior on a per model basis.  For instance if you want a bucket that will hold
+      # only Photos you can do this:
+      #
+      #   class Photo < ActiveRecord::Base
+      #     has_attachment :storage => :s3, :bucket_key => :photo_bucket_name
+      #   end
+      #
+      # And then your amazon_s3.yml file needs to look like this.
+      #
+      #   development:
+      #     bucket_name: appname_development
+      #     access_key_id: <your key>
+      #     secret_access_key: <your key>
+      #
+      #   test:
+      #     bucket_name: appname_test
+      #     access_key_id: <your key>
+      #     secret_access_key: <your key>
+      #
+      #   production:
+      #     bucket_name: appname
+      #     photo_bucket_name: appname_photos
+      #     access_key_id: <your key>
+      #     secret_access_key: <your key>
+      #
+      #  If the bucket_key you specify is not there in a certain environment then attachment_fu will
+      #  default to the <tt>bucket_name</tt> key.  This way you only have to create special buckets
+      #  this can be helpful if you only need special buckets in certain environments.
+      #
       # === Permissions
       #
       # By default, files are stored on S3 with public access permissions. You can customize this using
-      # the <tt>:s3_access</tt> option to <tt>has_attachment</tt>. Available values are 
+      # the <tt>:s3_access</tt> option to <tt>has_attachment</tt>. Available values are
       # <tt>:private</tt>, <tt>:public_read_write</tt>, and <tt>:authenticated_read</tt>.
       #
       # === Other options
@@ -117,13 +158,23 @@ module Technoweenie # :nodoc:
       #
       # Niether <tt>base_path</tt> or <tt>full_filename</tt> include the bucket name as part of the path.
       # You can retrieve the bucket name using the <tt>bucket_name</tt> method.
+      # 
+      # === Accessing CloudFront URLs
+      # 
+      # You can get an object's CloudFront URL using the cloudfront_url accessor.  Using the example from above:
+      # @postcard.cloudfront_url # => http://XXXX.cloudfront.net/photos/1/mexico.jpg
+      #
+      # The resulting url is in the form: http://:distribution_domain/:table_name/:id/:file
+      #
+      # If you set :cloudfront to true in your model, the public_filename will be the CloudFront
+      # URL, not the S3 URL.
       module S3Backend
         class RequiredLibraryNotFoundError < StandardError; end
         class ConfigFileNotFoundError < StandardError; end
 
         def self.included(base) #:nodoc:
           mattr_reader :bucket_name, :s3_config
-          
+
           begin
             require 'aws/s3'
             include AWS::S3
@@ -133,20 +184,21 @@ module Technoweenie # :nodoc:
 
           begin
             @@s3_config_path = base.attachment_options[:s3_config_path] || (RAILS_ROOT + '/config/amazon_s3.yml')
-            @@s3_config = @@s3_config = YAML.load_file(@@s3_config_path)[RAILS_ENV].symbolize_keys
+            @@s3_config = @@s3_config = YAML.load(ERB.new(File.read(@@s3_config_path)).result)[RAILS_ENV].symbolize_keys
           #rescue
           #  raise ConfigFileNotFoundError.new('File %s not found' % @@s3_config_path)
           end
 
-          @@bucket_name = s3_config[:bucket_name]
+          bucket_key = base.attachment_options[:bucket_key]
+
+          if bucket_key and s3_config[bucket_key.to_sym]
+            eval_string = "def bucket_name()\n  \"#{s3_config[bucket_key.to_sym]}\"\nend"
+          else
+            eval_string = "def bucket_name()\n  \"#{s3_config[:bucket_name]}\"\nend"
+          end
+          base.class_eval(eval_string, __FILE__, __LINE__)
 
-          Base.establish_connection!(
-            :access_key_id     => s3_config[:access_key_id],
-            :secret_access_key => s3_config[:secret_access_key],
-            :server            => s3_config[:server],
-            :port              => s3_config[:port],
-            :use_ssl           => s3_config[:use_ssl]
-          )
+          Base.establish_connection!(s3_config.slice(:access_key_id, :secret_access_key, :server, :port, :use_ssl, :persistent, :proxy))
 
           # Bucket.create(@@bucket_name)
 
@@ -156,27 +208,35 @@ module Technoweenie # :nodoc:
         def self.protocol
           @protocol ||= s3_config[:use_ssl] ? 'https://' : 'http://'
         end
-        
+
         def self.hostname
           @hostname ||= s3_config[:server] || AWS::S3::DEFAULT_HOST
         end
-        
+
         def self.port_string
-          @port_string ||= s3_config[:port] == (s3_config[:use_ssl] ? 443 : 80) ? '' : ":#{s3_config[:port]}"
+          @port_string ||= (s3_config[:port].nil? || s3_config[:port] == (s3_config[:use_ssl] ? 443 : 80)) ? '' : ":#{s3_config[:port]}"
+        end
+        
+        def self.distribution_domain
+          @distribution_domain = s3_config[:distribution_domain]
         end
 
         module ClassMethods
           def s3_protocol
             Technoweenie::AttachmentFu::Backends::S3Backend.protocol
           end
-          
+
           def s3_hostname
             Technoweenie::AttachmentFu::Backends::S3Backend.hostname
           end
-          
+
           def s3_port_string
             Technoweenie::AttachmentFu::Backends::S3Backend.port_string
           end
+          
+          def cloudfront_distribution_domain
+            Technoweenie::AttachmentFu::Backends::S3Backend.distribution_domain
+          end
         end
 
         # Overwrites the base filename writer in order to store the old filename
@@ -202,7 +262,7 @@ module Technoweenie # :nodoc:
           File.join(base_path, thumbnail_name_for(thumbnail))
         end
 
-        # All public objects are accessible via a GET request to the S3 servers. You can generate a 
+        # All public objects are accessible via a GET request to the S3 servers. You can generate a
         # url for an object using the s3_url method.
         #
         #   @photo.s3_url
@@ -215,9 +275,29 @@ module Technoweenie # :nodoc:
         def s3_url(thumbnail = nil)
           File.join(s3_protocol + s3_hostname + s3_port_string, bucket_name, full_filename(thumbnail))
         end
-        alias :public_filename :s3_url
+        
+        # All public objects are accessible via a GET request to CloudFront. You can generate a
+        # url for an object using the cloudfront_url method.
+        #
+        #   @photo.cloudfront_url
+        #
+        # The resulting url is in the form: <tt>http://:distribution_domain/:table_name/:id/:file</tt> using
+        # the <tt>:distribution_domain</tt> variable set in the configuration parameters in <tt>RAILS_ROOT/config/amazon_s3.yml</tt>.
+        #
+        # The optional thumbnail argument will output the thumbnail's filename (if any).
+        def cloudfront_url(thumbnail = nil)
+          "http://" + cloudfront_distribution_domain + "/" + full_filename(thumbnail)
+        end
+        
+        def public_filename(*args)
+          if attachment_options[:cloudfront]
+            cloudfront_url(args)
+          else
+            s3_url(args)
+          end
+        end
 
-        # All private objects are accessible via an authenticated GET request to the S3 servers. You can generate an 
+        # All private objects are accessible via an authenticated GET request to the S3 servers. You can generate an
         # authenticated url for an object like this:
         #
         #   @photo.authenticated_s3_url
@@ -229,7 +309,7 @@ module Technoweenie # :nodoc:
         #
         #   # Absolute expiration date (October 13th, 2025)
         #   @photo.authenticated_s3_url(:expires => Time.mktime(2025,10,13).to_i)
-        #   
+        #
         #   # Expiration in five hours from now
         #   @photo.authenticated_s3_url(:expires_in => 5.hours)
         #
@@ -242,8 +322,9 @@ module Technoweenie # :nodoc:
         #
         #   @photo.authenticated_s3_url('thumbnail', :expires_in => 5.hours, :use_ssl => true)
         def authenticated_s3_url(*args)
-          thumbnail = args.first.is_a?(String) ? args.first : nil
-          options   = args.last.is_a?(Hash)    ? args.last  : {}
+          options   = args.extract_options!
+          options[:expires_in] = options[:expires_in].to_i if options[:expires_in]
+          thumbnail = args.shift
           S3Object.url_for(full_filename(thumbnail), bucket_name, options)
         end
 
@@ -258,14 +339,18 @@ module Technoweenie # :nodoc:
         def s3_protocol
           Technoweenie::AttachmentFu::Backends::S3Backend.protocol
         end
-        
+
         def s3_hostname
           Technoweenie::AttachmentFu::Backends::S3Backend.hostname
         end
-          
+
         def s3_port_string
           Technoweenie::AttachmentFu::Backends::S3Backend.port_string
         end
+        
+        def cloudfront_distribution_domain
+          Technoweenie::AttachmentFu::Backends::S3Backend.distribution_domain
+        end
 
         protected
           # Called in the after_destroy callback
@@ -275,7 +360,7 @@ module Technoweenie # :nodoc:
 
           def rename_file
             return unless @old_filename && @old_filename != filename
-            
+
             old_full_filename = File.join(base_path, @old_filename)
 
             S3Object.rename(
@@ -306,4 +391,4 @@ module Technoweenie # :nodoc:
       end
     end
   end
-end
\ No newline at end of file
+end
diff --git a/vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu/processors/core_image_processor.rb b/vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu/processors/core_image_processor.rb
new file mode 100644 (file)
index 0000000..fc85c31
--- /dev/null
@@ -0,0 +1,59 @@
+require 'red_artisan/core_image/processor'
+
+module Technoweenie # :nodoc:
+  module AttachmentFu # :nodoc:
+    module Processors
+      module CoreImageProcessor
+        def self.included(base)
+          base.send :extend, ClassMethods
+          base.alias_method_chain :process_attachment, :processing
+        end
+        
+        module ClassMethods
+          def with_image(file, &block)
+            block.call OSX::CIImage.from(file)
+          end
+        end
+                
+        protected
+          def process_attachment_with_processing
+            return unless process_attachment_without_processing
+            with_image do |img|
+              self.width  = img.extent.size.width  if respond_to?(:width)
+              self.height = img.extent.size.height if respond_to?(:height)
+              resize_image_or_thumbnail! img
+              callback_with_args :after_resize, img
+            end if image?
+          end
+
+          # Performs the actual resizing operation for a thumbnail
+          def resize_image(img, size)
+            processor = ::RedArtisan::CoreImage::Processor.new(img)
+            size = size.first if size.is_a?(Array) && size.length == 1
+            if size.is_a?(Fixnum) || (size.is_a?(Array) && size.first.is_a?(Fixnum))
+              if size.is_a?(Fixnum)
+                processor.fit(size)
+              else
+                processor.resize(size[0], size[1])
+              end
+            else
+              new_size = [img.extent.size.width, img.extent.size.height] / size.to_s
+              processor.resize(new_size[0], new_size[1])
+            end
+            
+            processor.render do |result|
+              self.width  = result.extent.size.width  if respond_to?(:width)
+              self.height = result.extent.size.height if respond_to?(:height)
+              
+              # Get a new temp_path for the image before saving
+              temp_paths.unshift Tempfile.new(random_tempfile_filename, Technoweenie::AttachmentFu.tempfile_path).path
+              result.save self.temp_path, OSX::NSJPEGFileType
+              self.size = File.size(self.temp_path)
+            end
+          end          
+      end
+    end
+  end
+end
+
+
diff --git a/vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu/processors/gd2_processor.rb b/vendor/plugins/attachment_fu/lib/technoweenie/attachment_fu/processors/gd2_processor.rb
new file mode 100644 (file)
index 0000000..6d8e7ba
--- /dev/null
@@ -0,0 +1,54 @@
+require 'rubygems'
+require 'gd2'
+module Technoweenie # :nodoc:
+  module AttachmentFu # :nodoc:
+    module Processors
+      module Gd2Processor
+        def self.included(base)
+          base.send :extend, ClassMethods
+          base.alias_method_chain :process_attachment, :processing
+        end
+        
+        module ClassMethods
+          # Yields a block containing a GD2 Image for the given binary data.
+          def with_image(file, &block)
+            im = GD2::Image.import(file)
+            block.call(im)
+          end
+        end
+
+        protected
+          def process_attachment_with_processing
+            return unless process_attachment_without_processing && image?
+            with_image do |img|
+              resize_image_or_thumbnail! img
+              self.width  = img.width
+              self.height = img.height
+              callback_with_args :after_resize, img
+            end
+          end
+
+          # Performs the actual resizing operation for a thumbnail
+          def resize_image(img, size)
+            size = size.first if size.is_a?(Array) && size.length == 1
+            if size.is_a?(Fixnum) || (size.is_a?(Array) && size.first.is_a?(Fixnum))
+              if size.is_a?(Fixnum)
+                # Borrowed from image science's #thumbnail method and adapted 
+                # for this.
+                scale = size.to_f / (img.width > img.height ? img.width.to_f : img.height.to_f)
+                img.resize!((img.width * scale).round(1), (img.height * scale).round(1), false)
+              else
+                img.resize!(size.first, size.last, false) 
+              end
+            else
+              w, h = [img.width, img.height] / size.to_s
+              img.resize!(w, h, false)
+            end
+            temp_paths.unshift random_tempfile_filename
+            self.size = img.export(self.temp_path)
+          end
+
+      end
+    end
+  end
+end
\ No newline at end of file
index 095283c292d121552544c35291219a954fdd6b1d..e46f37692a1f56a0bc60df93139264eca5db0c38 100644 (file)
@@ -9,7 +9,7 @@ module Technoweenie # :nodoc:
         end
 
         module ClassMethods
-          # Yields a block containing an RMagick Image for the given binary data.
+          # Yields a block containing an Image Science image for the given binary data.
           def with_image(file, &block)
             ::ImageScience.with_image file, &block
           end
@@ -34,7 +34,7 @@ module Technoweenie # :nodoc:
             # supports.
             filename.sub! /gif$/, 'png'
             content_type.sub!(/gif$/, 'png')
-            self.temp_path = write_to_temp_file(filename)
+            temp_paths.unshift write_to_temp_file(filename)
             grab_dimensions = lambda do |img|
               self.width  = img.width  if respond_to?(:width)
               self.height = img.height if respond_to?(:height)
index e5a534c54939986a2d45c1b826a989425063ff01..96bc5d776d5b8339042a3990100a7ab94bb0e4b3 100644 (file)
@@ -7,7 +7,7 @@ module Technoweenie # :nodoc:
           base.send :extend, ClassMethods
           base.alias_method_chain :process_attachment, :processing
         end
-        
         module ClassMethods
           # Yields a block containing an MiniMagick Image for the given binary data.
           def with_image(file, &block)
@@ -23,33 +23,109 @@ module Technoweenie # :nodoc:
             !binary_data.nil?
           end
         end
-
       protected
         def process_attachment_with_processing
           return unless process_attachment_without_processing
           with_image do |img|
             resize_image_or_thumbnail! img
-            self.width  = img[:width] if respond_to?(:width)
-            self.height = img[:height]  if respond_to?(:height)
+            self.width = img[:width] if respond_to?(:width)
+            self.height = img[:height] if respond_to?(:height)
             callback_with_args :after_resize, img
           end if image?
         end
-
         # Performs the actual resizing operation for a thumbnail
         def resize_image(img, size)
           size = size.first if size.is_a?(Array) && size.length == 1
-          if size.is_a?(Fixnum) || (size.is_a?(Array) && size.first.is_a?(Fixnum))
-            if size.is_a?(Fixnum)
-              size = [size, size]
-              img.resize(size.join('x'))
+          img.combine_options do |commands|
+            commands.strip unless attachment_options[:keep_profile]
+
+            # gif are not handled correct, this is a hack, but it seems to work.
+            if img.output =~ / GIF /
+              img.format("png")
+            end           
+            
+            if size.is_a?(Fixnum) || (size.is_a?(Array) && size.first.is_a?(Fixnum))
+              if size.is_a?(Fixnum)
+                size = [size, size]
+                commands.resize(size.join('x'))
+              else
+                commands.resize(size.join('x') + '!')
+              end
+            # extend to thumbnail size
+            elsif size.is_a?(String) and size =~ /e$/
+              size = size.gsub(/e/, '')
+              commands.resize(size.to_s + '>')
+              commands.background('#ffffff')
+              commands.gravity('center')
+              commands.extent(size)
+            # crop thumbnail, the smart way
+            elsif size.is_a?(String) and size =~ /c$/
+               size = size.gsub(/c/, '')
+              
+              # calculate sizes and aspect ratio
+              thumb_width, thumb_height = size.split("x")
+              thumb_width   = thumb_width.to_f
+              thumb_height  = thumb_height.to_f
+              
+              thumb_aspect = thumb_width.to_f / thumb_height.to_f
+              image_width, image_height = img[:width].to_f, img[:height].to_f
+              image_aspect = image_width / image_height
+              
+              # only crop if image is not smaller in both dimensions
+              unless image_width < thumb_width and image_height < thumb_height
+                command = calculate_offset(image_width,image_height,image_aspect,thumb_width,thumb_height,thumb_aspect)
+
+                # crop image
+                commands.extract(command)
+              end
+
+              # don not resize if image is not as height or width then thumbnail
+              if image_width < thumb_width or image_height < thumb_height                   
+                  commands.background('#ffffff')
+                  commands.gravity('center')
+                  commands.extent(size)
+              # resize image
+              else
+                commands.resize("#{size.to_s}")
+              end
+            # crop end
             else
-              img.resize(size.join('x') + '!')
+              commands.resize(size.to_s)
             end
+          end
+          temp_paths.unshift img
+        end
+
+        def calculate_offset(image_width,image_height,image_aspect,thumb_width,thumb_height,thumb_aspect)
+        # only crop if image is not smaller in both dimensions
+
+          # special cases, image smaller in one dimension then thumbsize
+          if image_width < thumb_width
+            offset = (image_height / 2) - (thumb_height / 2)
+            command = "#{image_width}x#{thumb_height}+0+#{offset}"
+          elsif image_height < thumb_height
+            offset = (image_width / 2) - (thumb_width / 2)
+            command = "#{thumb_width}x#{image_height}+#{offset}+0"
+
+          # normal thumbnail generation
+          # calculate height and offset y, width is fixed                 
+          elsif (image_aspect <= thumb_aspect or image_width < thumb_width) and image_height > thumb_height
+            height = image_width / thumb_aspect
+            offset = (image_height / 2) - (height / 2)
+            command = "#{image_width}x#{height}+0+#{offset}"
+          # calculate width and offset x, height is fixed
           else
-            img.resize(size.to_s)
+            width = image_height * thumb_aspect
+            offset = (image_width / 2) - (width / 2)
+            command = "#{width}x#{image_height}+#{offset}+0"
           end
-          self.temp_path = img
+          # crop image
+          command
         end
+
+
       end
     end
   end
index 7999edb69afbd66d43fcc88585f28246ae8aa643..53227b23b70c944ddae126a4ea5c95db95f8e5ed 100644 (file)
@@ -7,7 +7,7 @@ module Technoweenie # :nodoc:
           base.send :extend, ClassMethods
           base.alias_method_chain :process_attachment, :processing
         end
-        
+
         module ClassMethods
           # Yields a block containing an RMagick Image for the given binary data.
           def with_image(file, &block)
@@ -35,19 +35,23 @@ module Technoweenie # :nodoc:
             callback_with_args :after_resize, img
           end if image?
         end
-      
+
         # Performs the actual resizing operation for a thumbnail
         def resize_image(img, size)
           size = size.first if size.is_a?(Array) && size.length == 1 && !size.first.is_a?(Fixnum)
           if size.is_a?(Fixnum) || (size.is_a?(Array) && size.first.is_a?(Fixnum))
             size = [size, size] if size.is_a?(Fixnum)
             img.thumbnail!(*size)
+          elsif size.is_a?(String) && size =~ /^c.*$/ # Image cropping - example geometry string: c75x75
+            dimensions = size[1..size.size].split("x")
+            img.crop_resized!(dimensions[0].to_i, dimensions[1].to_i)
           else
-            img.change_geometry(size.to_s) { |cols, rows, image| image.resize!(cols, rows) }
+            img.change_geometry(size.to_s) { |cols, rows, image| image.resize!(cols<1 ? 1 : cols, rows<1 ? 1 : rows) }
           end
-          self.temp_path = write_to_temp_file(img.to_blob)
+          img.strip! unless attachment_options[:keep_profile]
+          temp_paths.unshift write_to_temp_file(img.to_blob)
         end
       end
     end
   end
-end
\ No newline at end of file
+end
diff --git a/vendor/plugins/attachment_fu/rackspace_cloudfiles.yml.tpl b/vendor/plugins/attachment_fu/rackspace_cloudfiles.yml.tpl
new file mode 100644 (file)
index 0000000..ede689b
--- /dev/null
@@ -0,0 +1,14 @@
+development:
+    container_name: appname_development
+    username:
+    api_key: 
+
+test:
+    container_name: appname_test
+    username: 
+    api_key: 
+
+production:
+    container_name: appname_production
+    username: 
+    api_key: 
diff --git a/vendor/plugins/attachment_fu/test/amazon_s3.yml b/vendor/plugins/attachment_fu/test/amazon_s3.yml
deleted file mode 100644 (file)
index 0024c8e..0000000
+++ /dev/null
@@ -1,6 +0,0 @@
-test:
-  bucket_name: afu
-  access_key_id: YOURACCESSKEY
-  secret_access_key: YOURSECRETACCESSKEY
-  server: 127.0.0.1
-  port: 3002
\ No newline at end of file
index d3250c1a9f3eac38ae4e8409fbca2cbaee6ca53d..8b6be2eb828c1b52addd249b5e1a5868215f7941 100644 (file)
@@ -1,4 +1,5 @@
 require File.expand_path(File.join(File.dirname(__FILE__), '..', 'test_helper'))
+require 'digest/sha2'
 
 class FileSystemTest < Test::Unit::TestCase
   include BaseAttachmentTests
@@ -52,7 +53,7 @@ class FileSystemTest < Test::Unit::TestCase
     assert_not_created do
       use_temp_file 'files/rails.png' do |file|
         attachment.filename        = 'rails2.png'
-        attachment.temp_path = File.join(fixture_path, file)
+        attachment.temp_paths.unshift File.join(fixture_path, file)
         attachment.save!
         assert  File.exists?(attachment.full_filename), "#{attachment.full_filename} does not exist"    
         assert !File.exists?(old_filename),             "#{old_filename} still exists"
@@ -77,4 +78,66 @@ class FileSystemTest < Test::Unit::TestCase
   end
   
   test_against_subclass :test_should_delete_old_file_when_renaming, FileAttachment
-end
\ No newline at end of file
+  
+  def test_path_partitioning_works_on_integer_id(klass = FileAttachment)
+    attachment_model klass
+    
+    # Create a random attachment object, doesn't matter what.
+    attachment = upload_file :filename => '/files/rails.png'
+    old_id = attachment.id
+    attachment.id = 1
+    
+    begin
+      assert_equal ["0000", "0001", "bar.txt"], attachment.send(:partitioned_path, "bar.txt")
+    ensure
+      attachment.id = old_id
+    end
+  end
+  
+  test_against_subclass :test_path_partitioning_works_on_integer_id, FileAttachment
+  
+  def test_path_partitioning_with_string_id_works_by_generating_hash(klass = FileAttachmentWithStringId)
+    attachment_model klass
+    
+    # Create a random attachment object, doesn't matter what.
+    attachment = upload_file :filename => '/files/rails.png'
+    old_id = attachment.id
+    attachment.id = "hello world some long string"
+    hash = Digest::SHA512.hexdigest("hello world some long string")
+    
+    begin
+      assert_equal [
+          hash[0..31],
+          hash[32..63],
+          hash[64..95],
+          hash[96..127],
+          "bar.txt"
+        ], attachment.send(:partitioned_path, "bar.txt")
+    ensure
+      attachment.id = old_id
+    end
+  end
+  
+  test_against_subclass :test_path_partitioning_with_string_id_works_by_generating_hash, FileAttachmentWithStringId
+  
+  def test_path_partition_string_id_hashing_is_turned_off_if_id_is_uuid(klass = FileAttachmentWithUuid)
+    attachment_model klass
+    
+    # Create a random attachment object, doesn't matter what.
+    attachment = upload_file :filename => '/files/rails.png'
+    old_id = attachment.id
+    attachment.id = "0c0743b698483569dc65909a8cdb3bf9"
+    
+    begin
+      assert_equal [
+          "0c0743b698483569",
+          "dc65909a8cdb3bf9",
+          "bar.txt"
+        ], attachment.send(:partitioned_path, "bar.txt")
+    ensure
+      attachment.id = old_id
+    end
+  end
+  
+  test_against_subclass :test_path_partition_string_id_hashing_is_turned_off_if_id_is_uuid, FileAttachmentWithUuid
+end
diff --git a/vendor/plugins/attachment_fu/test/backends/remote/cloudfiles_test.rb b/vendor/plugins/attachment_fu/test/backends/remote/cloudfiles_test.rb
new file mode 100644 (file)
index 0000000..f36dc09
--- /dev/null
@@ -0,0 +1,102 @@
+require File.expand_path(File.join(File.dirname(__FILE__), '..', '..', 'test_helper'))
+require 'net/http'
+
+class CloudfilesTest < Test::Unit::TestCase
+  def self.test_CloudFiles?
+    true unless ENV["TEST_CLOUDFILES"] == "false"
+  end
+  
+  if test_CloudFiles? && File.exist?(File.join(File.dirname(__FILE__), '../../rackspace_cloudfiles.yml'))
+    include BaseAttachmentTests
+    attachment_model CloudFilesAttachment
+
+    def test_should_create_correct_container_name(klass = CloudFilesAttachment)
+      attachment_model klass
+      attachment = upload_file :filename => '/files/rails.png'
+      assert_equal attachment.cloudfiles_config[:container_name], attachment.container_name
+    end
+
+    test_against_subclass :test_should_create_correct_container_name, CloudFilesAttachment
+    
+    def test_should_create_default_path_prefix(klass = CloudFilesAttachment)
+      attachment_model klass
+      attachment = upload_file :filename => '/files/rails.png'
+      assert_equal File.join(attachment_model.table_name, attachment.attachment_path_id), attachment.base_path
+    end
+
+    test_against_subclass :test_should_create_default_path_prefix, CloudFilesAttachment
+    
+    def test_should_create_custom_path_prefix(klass = CloudFilesWithPathPrefixAttachment)
+      attachment_model klass
+      attachment = upload_file :filename => '/files/rails.png'
+      assert_equal File.join('some/custom/path/prefix', attachment.attachment_path_id), attachment.base_path
+    end
+
+    test_against_subclass :test_should_create_custom_path_prefix, CloudFilesWithPathPrefixAttachment
+    
+    
+    def test_should_create_valid_url(klass = CloudFilesAttachment)
+      attachment_model klass
+      attachment = upload_file :filename => '/files/rails.png'
+      assert_match(%r!http://cdn.cloudfiles.mosso.com/(.*?)/cloud_files_attachments/1/rails.png!, attachment.cloudfiles_url)
+    end
+    
+    test_against_subclass :test_should_create_valid_url, CloudFilesAttachment
+    
+    def test_should_save_attachment(klass = CloudFilesAttachment)
+      attachment_model klass
+      assert_created do
+        attachment = upload_file :filename => '/files/rails.png'
+        assert_valid attachment
+        assert attachment.image?
+        assert !attachment.size.zero?
+        assert_kind_of Net::HTTPOK, http_response_for(attachment.cloudfiles_url)
+      end
+    end
+
+    test_against_subclass :test_should_save_attachment, CloudFilesAttachment
+    
+    def test_should_delete_attachment_from_cloud_files_when_attachment_record_destroyed(klass = CloudFilesAttachment)
+      attachment_model klass
+      attachment = upload_file :filename => '/files/rails.png'
+
+      urls = [attachment.cloudfiles_url] + attachment.thumbnails.collect(&:cloudfiles_url)
+
+      urls.each {|url| assert_kind_of Net::HTTPOK, http_response_for(url) }
+      attachment.destroy
+      urls.each do |url|
+        begin
+          http_response_for(url)
+        rescue Net::HTTPForbidden, Net::HTTPNotFound
+          nil
+        end
+      end
+    end
+
+    test_against_subclass :test_should_delete_attachment_from_cloud_files_when_attachment_record_destroyed, CloudFilesAttachment
+    
+    
+    
+    protected
+      def http_response_for(url)
+        url = URI.parse(url)
+        Net::HTTP.start(url.host, url.port) {|http| http.request_head(url.path) }
+      end
+      
+      def s3_protocol
+        Technoweenie::AttachmentFu::Backends::S3Backend.protocol
+      end
+      
+      def s3_hostname
+        Technoweenie::AttachmentFu::Backends::S3Backend.hostname
+      end
+
+      def s3_port_string
+        Technoweenie::AttachmentFu::Backends::S3Backend.port_string
+      end
+  else
+    def test_flunk_s3
+      puts "s3 config file not loaded, tests not running"
+    end
+  end
+end
\ No newline at end of file
index 82520a082a2bbbec07307c0f04e88de651f9dc63..c7cb4f952d787d647ebee99c92c166d2d3ab607e 100644 (file)
@@ -2,7 +2,11 @@ require File.expand_path(File.join(File.dirname(__FILE__), '..', '..', 'test_hel
 require 'net/http'
 
 class S3Test < Test::Unit::TestCase
-  if File.exist?(File.join(File.dirname(__FILE__), '../../amazon_s3.yml'))
+  def self.test_S3?
+    true unless ENV["TEST_S3"] == "false"
+  end
+  
+  if test_S3? && File.exist?(File.join(File.dirname(__FILE__), '../../amazon_s3.yml'))
     include BaseAttachmentTests
     attachment_model S3Attachment
 
@@ -45,6 +49,18 @@ class S3Test < Test::Unit::TestCase
     end
 
     test_against_subclass :test_should_create_authenticated_url, S3Attachment
+    
+    def test_should_create_authenticated_url_for_thumbnail(klass = S3Attachment)
+      attachment_model klass
+      attachment = upload_file :filename => '/files/rails.png'
+      ['large', :large].each do |thumbnail|
+        assert_match(
+          /^http.+rails_large\.png.+AWSAccessKeyId.+Expires.+Signature/, 
+          attachment.authenticated_s3_url(thumbnail), 
+          "authenticated_s3_url failed with #{thumbnail.class} parameter"
+        )
+      end
+    end
 
     def test_should_save_attachment(klass = S3Attachment)
       attachment_model klass
index c9dbbd7a1018cc2477369f3acee202635a22855c..a35ab1c63eab75753eaf6a29d934d0f91aa2d00a 100644 (file)
@@ -12,13 +12,26 @@ module BaseAttachmentTests
     end
   end
   
+  def test_should_create_file_from_merb_temp_file
+    assert_created do
+      attachment = upload_merb_file :filename => '/files/foo.txt'
+      assert_valid attachment
+      assert !attachment.db_file.new_record? if attachment.respond_to?(:db_file)
+      assert  attachment.image?
+      assert !attachment.size.zero?
+      #assert_equal 3, attachment.size
+      assert_nil      attachment.width
+      assert_nil      attachment.height
+    end
+  end
+  
   def test_reassign_attribute_data
     assert_created 1 do
       attachment = upload_file :filename => '/files/rails.png'
       assert_valid attachment
       assert attachment.size > 0, "no data was set"
       
-      attachment.temp_data = 'wtf'
+      attachment.set_temp_data 'wtf'
       assert attachment.save_attachment?
       attachment.save!
       
@@ -32,7 +45,7 @@ module BaseAttachmentTests
       assert_valid attachment
       assert attachment.size > 0, "no data was set"
       
-      attachment.temp_data = nil
+      attachment.set_temp_data nil
       assert !attachment.save_attachment?
     end
   end
@@ -42,7 +55,7 @@ module BaseAttachmentTests
     assert_not_created do # no new db_file records
       use_temp_file 'files/rails.png' do |file|
         attachment.filename = 'rails2.png'
-        attachment.temp_path = File.join(fixture_path, file)
+        attachment.temp_paths.unshift File.join(fixture_path, file)
         attachment.save!
       end
     end
@@ -54,4 +67,11 @@ module BaseAttachmentTests
     assert !attachment.save_attachment?
     assert_nothing_raised { attachment.save! }
   end
+  
+  def test_should_handle_nil_file_upload
+    attachment = attachment_model.create :uploaded_data => ''
+    assert_raise ActiveRecord::RecordInvalid do
+      attachment.save!
+    end
+  end
 end
\ No newline at end of file
index f8f881cbc0c70e88b84ae76bd1009f784630c6f5..70a8bdab5aff4a156c6e711ce371a2b07fef81ee 100644 (file)
@@ -24,8 +24,8 @@ class BasicTest < Test::Unit::TestCase
   def test_should_normalize_content_types_to_array
     assert_equal %w(pdf), PdfAttachment.attachment_options[:content_type]
     assert_equal %w(pdf doc txt), DocAttachment.attachment_options[:content_type]
-    assert_equal ['image/jpeg', 'image/pjpeg', 'image/gif', 'image/png', 'image/x-png', 'image/jpg'], ImageAttachment.attachment_options[:content_type]
-    assert_equal ['pdf', 'image/jpeg', 'image/pjpeg', 'image/gif', 'image/png', 'image/x-png', 'image/jpg'], ImageOrPdfAttachment.attachment_options[:content_type]
+    assert_equal Technoweenie::AttachmentFu.content_types, ImageAttachment.attachment_options[:content_type]
+    assert_equal ['pdf'] + Technoweenie::AttachmentFu.content_types, ImageOrPdfAttachment.attachment_options[:content_type]
   end
   
   def test_should_sanitize_content_type
@@ -42,6 +42,12 @@ class BasicTest < Test::Unit::TestCase
 
     @attachment.filename = 'f o!O-.bar'
     assert_equal 'f_o_O-.bar', @attachment.filename
+    
+    @attachment.filename = 'sheeps_says_bææ'
+    assert_equal 'sheeps_says_b__', @attachment.filename
+
+    @attachment.filename = nil
+    assert_nil @attachment.filename
   end
   
   def test_should_convert_thumbnail_name
@@ -61,4 +67,4 @@ class BasicTest < Test::Unit::TestCase
       klass.has_attachment :thumbnails => []
     end
   end
-end
\ No newline at end of file
+end
index 15b185209b27794d9a2e7430cd1a1984a7eac3cf..6c58554175934d1413dd09019f3c1027e81416dc 100644 (file)
@@ -24,6 +24,16 @@ class OrphanAttachmentTest < Test::Unit::TestCase
     end
   end
   
+  def test_should_create_file_from_merb_temp_file
+    assert_created do
+      attachment = upload_merb_file :filename => '/files/foo.txt'
+      assert_valid attachment
+      assert !attachment.db_file.new_record? if attachment.respond_to?(:db_file)
+      assert  attachment.image?
+      assert !attachment.size.zero?
+    end
+  end
+  
   def test_should_create_image_from_uploaded_file_with_custom_content_type
     assert_created do
       attachment = upload_file :content_type => 'foo/bar', :filename => '/files/rails.png'
index 77d60c3f751ff9b01a2b116ce0acbb773ad44e57..4348300d2a29fce8fe657271a6ef79bfa8d60b50 100644 (file)
@@ -35,7 +35,7 @@ end
 class ImageWithThumbsAttachment < Attachment
   has_attachment :thumbnails => { :thumb => [50, 50], :geometry => 'x50' }, :resize_to => [55,55]
   after_resize do |record, img|
-    record.aspect_ratio = img.columns.to_f / img.rows.to_f
+   # record.aspect_ratio = img.columns.to_f / img.rows.to_f
   end
 end
 
@@ -44,6 +44,38 @@ class FileAttachment < ActiveRecord::Base
   validates_as_attachment
 end
 
+class FileAttachmentWithStringId < ActiveRecord::Base
+  set_table_name 'file_attachments_with_string_id'
+  has_attachment :path_prefix => 'vendor/plugins/attachment_fu/test/files', :processor => :rmagick
+  validates_as_attachment
+  
+  before_validation :auto_generate_id
+  before_save :auto_generate_id
+  @@last_id = 0
+  
+  private
+    def auto_generate_id
+      @@last_id += 1
+      self.id = "id_#{@@last_id}"
+    end
+end
+
+class FileAttachmentWithUuid < ActiveRecord::Base
+  set_table_name 'file_attachments_with_string_id'
+  has_attachment :path_prefix => 'vendor/plugins/attachment_fu/test/files', :processor => :rmagick, :uuid_primary_key => true
+  validates_as_attachment
+  
+  before_validation :auto_generate_id
+  before_save :auto_generate_id
+  @@last_id = 0
+  
+  private
+    def auto_generate_id
+      @@last_id += 1
+      self.id = "%0127dx" % @@last_id
+    end
+end
+
 class ImageFileAttachment < FileAttachment
   has_attachment :path_prefix => 'vendor/plugins/attachment_fu/test/files',
     :content_type => :image, :resize_to => [50,50]
@@ -53,7 +85,7 @@ class ImageWithThumbsFileAttachment < FileAttachment
   has_attachment :path_prefix => 'vendor/plugins/attachment_fu/test/files',
     :thumbnails => { :thumb => [50, 50], :geometry => 'x50' }, :resize_to => [55,55]
   after_resize do |record, img|
-    record.aspect_ratio = img.columns.to_f / img.rows.to_f
+  #  record.aspect_ratio = img.columns.to_f / img.rows.to_f
   end
 end
 
@@ -94,6 +126,16 @@ rescue MissingSourceFile
   puts "no ImageScience"
 end
 
+begin
+  class CoreImageAttachment < ActiveRecord::Base
+    has_attachment :path_prefix => 'vendor/plugins/attachment_fu/test/files',
+      :processor => :core_image, :thumbnails => { :thumb => [50, 51], :geometry => '31>' }, :resize_to => 55
+  end
+rescue MissingSourceFile
+  puts $!.message
+  puts "no CoreImage"
+end
+
 begin
   class MiniMagickAttachment < ActiveRecord::Base
     has_attachment :path_prefix => 'vendor/plugins/attachment_fu/test/files',
@@ -104,24 +146,81 @@ rescue MissingSourceFile
   puts "no Mini Magick"
 end
 
+begin
+  class GD2Attachment < ActiveRecord::Base
+    has_attachment :path_prefix => 'vendor/plugins/attachment_fu/test/files',
+      :processor => :gd2, :thumbnails => { :thumb => [50, 51], :geometry => '31>' }, :resize_to => 55
+  end
+rescue MissingSourceFile
+  puts $!.message
+  puts "no GD2"
+end
+
+
 begin
   class MiniMagickAttachment < ActiveRecord::Base
     has_attachment :path_prefix => 'vendor/plugins/attachment_fu/test/files',
       :processor => :mini_magick, :thumbnails => { :thumb => [50, 51], :geometry => '31>' }, :resize_to => 55
   end
+  class ImageThumbnailCrop < MiniMagickAttachment
+    has_attachment :path_prefix => 'vendor/plugins/attachment_fu/test/files',
+    :thumbnails => { :square => "50x50c", :vertical => "30x60c", :horizontal => "60x30c"}
+    
+    # TODO this is a bad duplication, this method is in the MiniMagick Processor
+    def self.calculate_offset(image_width,image_height,image_aspect,thumb_width,thumb_height,thumb_aspect)
+    # only crop if image is not smaller in both dimensions
+
+      # special cases, image smaller in one dimension then thumbsize
+      if image_width < thumb_width
+        offset = (image_height / 2) - (thumb_height / 2)
+        command = "#{image_width}x#{thumb_height}+0+#{offset}"
+      elsif image_height < thumb_height
+        offset = (image_width / 2) - (thumb_width / 2)
+        command = "#{thumb_width}x#{image_height}+#{offset}+0"
+
+      # normal thumbnail generation
+      # calculate height and offset y, width is fixed                 
+      elsif (image_aspect <= thumb_aspect or image_width < thumb_width) and image_height > thumb_height
+        height = image_width / thumb_aspect
+        offset = (image_height / 2) - (height / 2)
+        command = "#{image_width}x#{height}+0+#{offset}"
+      # calculate width and offset x, height is fixed
+      else
+        width = image_height * thumb_aspect
+        offset = (image_width / 2) - (width / 2)
+        command = "#{width}x#{image_height}+#{offset}+0"
+      end
+      # crop image
+      command
+    end
+  end
+
 rescue MissingSourceFile
 end
 
+
+
 begin
   class S3Attachment < ActiveRecord::Base
     has_attachment :storage => :s3, :processor => :rmagick, :s3_config_path => File.join(File.dirname(__FILE__), '../amazon_s3.yml')
     validates_as_attachment
   end
+  
+  class CloudFilesAttachment < ActiveRecord::Base
+    has_attachment :storage => :cloud_files, :processor => :rmagick, :cloudfiles_config_path => File.join(File.dirname(__FILE__), '../rackspace_cloudfiles.yml')
+    validates_as_attachment
+  end
 
   class S3WithPathPrefixAttachment < S3Attachment
     has_attachment :storage => :s3, :path_prefix => 'some/custom/path/prefix', :processor => :rmagick
     validates_as_attachment
   end
-rescue Technoweenie::AttachmentFu::Backends::S3Backend::ConfigFileNotFoundError
+  
+  class CloudFilesWithPathPrefixAttachment < CloudFilesAttachment
+    has_attachment :storage => :cloud_files, :path_prefix => 'some/custom/path/prefix', :processor => :rmagick
+    validates_as_attachment
+  end
+  
+rescue
   puts "S3 error: #{$!}"
 end
index ade4f489cf44fa6a0f4162a7de893b9af149959b..aebb41564eb3ae2049172a2ea3c642ff00809860 100644 (file)
@@ -23,6 +23,13 @@ class GeometryTest < Test::Unit::TestCase
       "100" => [100, 128]
   end
   
+  def test_should_resize_no_height_with_x
+    assert_geometry 50, 64,
+      "50x"  => [50, 64],
+      "60x"  => [60, 77],
+      "100x" => [100, 128]
+  end
+  
   def test_should_resize_with_percent
     assert_geometry 50, 64,
       "50x50%"   => [25, 32],
diff --git a/vendor/plugins/attachment_fu/test/processors/core_image_test.rb b/vendor/plugins/attachment_fu/test/processors/core_image_test.rb
new file mode 100644 (file)
index 0000000..1e3976f
--- /dev/null
@@ -0,0 +1,37 @@
+require File.expand_path(File.join(File.dirname(__FILE__), '..', 'test_helper'))
+
+class CoreImageTest < Test::Unit::TestCase
+  attachment_model CoreImageAttachment
+
+  if Object.const_defined?(:OSX)
+    def test_should_resize_image
+      attachment = upload_file :filename => '/files/rails.png'
+      assert_valid attachment
+      assert attachment.image?
+      # test core image thumbnail
+      assert_equal 42, attachment.width
+      assert_equal 55, attachment.height
+      
+      thumb      = attachment.thumbnails.detect { |t| t.filename =~ /_thumb/ }
+      geo        = attachment.thumbnails.detect { |t| t.filename =~ /_geometry/ }
+      
+      # test exact resize dimensions
+      assert_equal 50, thumb.width
+      assert_equal 51, thumb.height
+      
+      # test geometry string
+      assert_equal 31, geo.width
+      assert_equal 41, geo.height
+      
+      # This makes sure that we didn't overwrite the original file
+      # and will end up with a thumbnail instead of the original
+      assert_equal 42, attachment.width
+      assert_equal 55, attachment.height
+      
+    end
+  else
+    def test_flunk
+      puts "CoreImage not loaded, tests not running"
+    end
+  end
+end
\ No newline at end of file
diff --git a/vendor/plugins/attachment_fu/test/processors/gd2_test.rb b/vendor/plugins/attachment_fu/test/processors/gd2_test.rb
new file mode 100644 (file)
index 0000000..298853b
--- /dev/null
@@ -0,0 +1,31 @@
+require File.expand_path(File.join(File.dirname(__FILE__), '..', 'test_helper'))
+
+class GD2Test < Test::Unit::TestCase
+  attachment_model GD2Attachment
+
+  if Object.const_defined?(:GD2)
+    def test_should_resize_image
+      attachment = upload_file :filename => '/files/rails.png'
+      assert_valid attachment
+      assert attachment.image?
+      # test gd2 thumbnail
+      assert_equal 43, attachment.width
+      assert_equal 55, attachment.height
+      
+      thumb = attachment.thumbnails.detect { |t| t.filename =~ /_thumb/ }
+      geo   = attachment.thumbnails.detect { |t| t.filename =~ /_geometry/ }
+      
+      # test exact resize dimensions
+      assert_equal 50, thumb.width
+      assert_equal 51, thumb.height
+      
+      # test geometry string
+      assert_equal 31, geo.width
+      assert_equal 40, geo.height
+    end
+  else
+    def test_flunk
+      puts "GD2 not loaded, tests not running"
+    end
+  end
+end
\ No newline at end of file
index 244a4a2331fe1ae93d34ddcd2156fa697fcaabfa..710ea41020a394c8ee3341646bfa1bb3e2a1cb9c 100644 (file)
@@ -23,9 +23,81 @@ class MiniMagickTest < Test::Unit::TestCase
       assert_equal 31, geo.width
       assert_equal 40, geo.height
     end
+
+    def test_should_crop_image(klass = ImageThumbnailCrop)
+      attachment_model klass
+      attachment = upload_file :filename => '/files/rails.png'
+      assert_valid attachment
+      assert  attachment.image?
+    #  has_attachment :thumbnails => { :square => "50x50c", :vertical => "30x60c", :horizontal => "60x30c"}
+
+      square      = attachment.thumbnails.detect { |t| t.filename =~ /_square/ }
+      vertical    = attachment.thumbnails.detect { |t| t.filename =~ /_vertical/ }
+      horizontal  = attachment.thumbnails.detect { |t| t.filename =~ /_horizontal/ }
+      
+      # test excat resize
+      assert_equal 50, square.width
+      assert_equal 50, square.height
+
+      assert_equal 30, vertical.width
+      assert_equal 60, vertical.height
+
+      assert_equal 60, horizontal.width
+      assert_equal 30, horizontal.height
+    end
+    
+    # tests the first step in resize, crop the image in original size to right format
+    def test_should_crop_image_right(klass = ImageThumbnailCrop)      
+      @@testcases.collect do |testcase| 
+        image_width, image_height, thumb_width, thumb_height = testcase[:data]
+        image_aspect, thumb_aspect = image_width/image_height, thumb_width/thumb_height
+        crop_comand = klass.calculate_offset(image_width, image_height, image_aspect, thumb_width, thumb_height,thumb_aspect)
+        # pattern matching on crop command
+        if testcase.has_key?(:height) 
+          assert crop_comand.match(/^#{image_width}x#{testcase[:height]}\+0\+#{testcase[:yoffset]}$/)
+        else 
+          assert crop_comand.match(/^#{testcase[:width]}x#{image_height}\+#{testcase[:xoffset]}\+0$/)
+        end
+      end
+    end
+
   else
     def test_flunk
       puts "MiniMagick not loaded, tests not running"
     end
   end
+
+  @@testcases = [
+    # image_aspect <= 1 && thumb_aspect >= 1  
+    {:data => [10.0,40.0,2.0,1.0], :height => 5.0, :yoffset => 17.5}, #   1b
+    {:data => [10.0,40.0,1.0,1.0], :height => 10.0, :yoffset => 15.0}, #  1b
+
+    # image_aspect < 1 && thumb_aspect < 1
+    {:data => [10.0,40.0,1.0,2.0], :height => 20.0, :yoffset => 10.0}, # 1a
+    {:data => [2.0,3.0,1.0,2.0], :width => 1.5, :xoffset => 0.25}, # 1a
+
+    # image_aspect = thumb_aspect
+    {:data => [10.0,10.0,1.0,1.0], :height => 10.0, :yoffset => 0.0}, # QUADRAT 1c
+
+    # image_aspect >= 1 && thumb_aspect > 1     && image_aspect < thumb_aspect
+    {:data => [6.0,3.0,4.0,1.0], :height => 1.5, :yoffset => 0.75}, # 2b  
+    {:data => [6.0,6.0,4.0,1.0], :height => 1.5, :yoffset => 2.25}, # 2b  
+
+    # image_aspect > 1 && thumb_aspect > 1     && image_aspect > thumb_aspect
+    {:data => [9.0,3.0,2.0,1.0], :width => 6.0, :xoffset => 1.5}, # 2a
+
+    # image_aspect > 1 && thumb_aspect < 1 && image_aspect < thumb_aspect
+    {:data => [10.0,5.0,0.1,2.0], :width => 0.25, :xoffset => 4.875}, # 4
+    {:data => [10.0,5.0,1.0,2.0], :width => 2.5, :xoffset => 3.75}, # 4
+
+    # image_aspect > 1 && thumb_aspect > 1     && image_aspect > thumb_aspect
+    {:data => [9.0,3.0,2.0,1.0], :width => 6.0, :xoffset => 1.5}, # 3a    
+    # image_aspect > 1 && thumb_aspect > 1     && image_aspect < thumb_aspect
+    {:data => [9.0,3.0,5.0,1.0], :height => 1.8, :yoffset => 0.6} # 3a
+  ]
+
+
+
+
+
 end
index 13d177af50ef754c075e00b0e2b59225e3b04cbc..8e07f2102bdaa7dd128e85d194d614bd3cca5fc4 100644 (file)
@@ -157,12 +157,14 @@ class RmagickTest < Test::Unit::TestCase
         assert_valid attachment
       end
       assert_kind_of ImageThumbnail,  attachment.thumbnails.first
-      assert_equal attachment.id,     attachment.thumbnails.first.parent.id
-      assert_kind_of FileAttachment,  attachment.thumbnails.first.parent
+      if attachment.thumbnails.first.respond_to?(:parent)
+        assert_equal attachment.id,     attachment.thumbnails.first.parent.id
+        assert_kind_of FileAttachment,  attachment.thumbnails.first.parent
+      end
       assert_equal 'rails_thumb.png', attachment.thumbnails.first.filename
       assert_equal attachment.thumbnails.first.full_filename, attachment.full_filename(attachment.thumbnails.first.thumbnail),
         "#full_filename does not use thumbnail class' path."
-      assert_equal attachment.destroy attachment
+      assert_equal attachment.destroy, attachment
     end
     
     test_against_subclass :test_should_use_thumbnail_subclass, ImageWithThumbsClassFileAttachment
@@ -179,7 +181,7 @@ class RmagickTest < Test::Unit::TestCase
       assert_not_created do
         use_temp_file "files/rails.png" do |file|
           attachment.filename        = 'rails2.png'
-          attachment.temp_path = File.join(fixture_path, file)
+          attachment.temp_paths.unshift File.join(fixture_path, file)
           attachment.save
           new_filenames = [attachment.reload.full_filename] + attachment.thumbnails.collect { |t| t.reload.full_filename }
           new_filenames.each { |f| assert  File.exists?(f), "#{f} does not exist" }
@@ -201,6 +203,14 @@ class RmagickTest < Test::Unit::TestCase
     
     test_against_subclass :test_should_delete_file_when_in_file_system_when_attachment_record_destroyed, ImageWithThumbsFileAttachment
     
+    def test_should_have_full_filename_method(klass = FileAttachment)
+      attachment_model klass
+      attachment = upload_file :filename => '/files/rails.png'
+      assert_respond_to attachment, :full_filename
+    end
+    
+    test_against_subclass :test_should_have_full_filename_method, FileAttachment
+    
     def test_should_overwrite_old_thumbnail_records_when_updating(klass = ImageWithThumbsAttachment)
       attachment_model klass
       attachment = nil
@@ -210,7 +220,11 @@ class RmagickTest < Test::Unit::TestCase
       assert_not_created do # no new db_file records
         use_temp_file "files/rails.png" do |file|
           attachment.filename             = 'rails2.png'
-          attachment.temp_path = File.join(fixture_path, file)
+          # The above test (#test_should_have_full_filename_method) to pass before be can set the temp_path below -- 
+          # #temp_path calls #full_filename, which is not getting mixed into the attachment.  Maybe we don't need to
+          # set temp_path at all?
+          #
+          # attachment.temp_paths.unshift File.join(fixture_path, file)
           attachment.save!
         end
       end
@@ -238,4 +252,4 @@ class RmagickTest < Test::Unit::TestCase
       puts "RMagick not installed, no tests running"
     end
   end
-end
\ No newline at end of file
+end
index b2e284d5ca203e89763ff93dfef1a3db0d96ac1e..b7666f5b9366e4ba77fad6dd0d7bcd9636ee6946 100644 (file)
@@ -22,6 +22,30 @@ ActiveRecord::Schema.define(:version => 0) do
     t.column :type,            :string
     t.column :aspect_ratio,    :float
   end
+  
+  create_table :file_attachments_with_string_id, :id => false, :force => true do |t|
+    t.column :id,              :string
+    t.column :parent_id,       :string
+    t.column :thumbnail,       :string 
+    t.column :filename,        :string, :limit => 255
+    t.column :content_type,    :string, :limit => 255
+    t.column :size,            :integer
+    t.column :width,           :integer
+    t.column :height,          :integer
+    t.column :type,            :string
+    t.column :aspect_ratio,    :float
+  end
+
+  create_table :gd2_attachments, :force => true do |t|
+    t.column :parent_id,       :integer
+    t.column :thumbnail,       :string 
+    t.column :filename,        :string, :limit => 255
+    t.column :content_type,    :string, :limit => 255
+    t.column :size,            :integer
+    t.column :width,           :integer
+    t.column :height,          :integer
+    t.column :type,            :string
+  end
 
   create_table :image_science_attachments, :force => true do |t|
     t.column :parent_id,       :integer
@@ -34,6 +58,17 @@ ActiveRecord::Schema.define(:version => 0) do
     t.column :type,            :string
   end
 
+  create_table :core_image_attachments, :force => true do |t|
+    t.column :parent_id,       :integer
+    t.column :thumbnail,       :string 
+    t.column :filename,        :string, :limit => 255
+    t.column :content_type,    :string, :limit => 255
+    t.column :size,            :integer
+    t.column :width,           :integer
+    t.column :height,          :integer
+    t.column :type,            :string
+  end
+  
   create_table :mini_magick_attachments, :force => true do |t|
     t.column :parent_id,       :integer
     t.column :thumbnail,       :string 
@@ -83,4 +118,17 @@ ActiveRecord::Schema.define(:version => 0) do
     t.column :type,            :string
     t.column :aspect_ratio,    :float
   end
-end
\ No newline at end of file
+  
+  create_table :cloud_files_attachments, :force => true do |t|
+    t.column :parent_id,       :integer
+    t.column :thumbnail,       :string 
+    t.column :filename,        :string, :limit => 255
+    t.column :content_type,    :string, :limit => 255
+    t.column :size,            :integer
+    t.column :width,           :integer
+    t.column :height,          :integer
+    t.column :type,            :string
+    t.column :aspect_ratio,    :float
+  end
+  
+end
index 66a0b72dcb51a717e46ab98bd88c6558cae5d697..5fe613188198182f1d74bf17ae99137927986717 100644 (file)
@@ -1,10 +1,10 @@
 $:.unshift(File.dirname(__FILE__) + '/../lib')
 
 ENV['RAILS_ENV'] = 'test'
+ENV['RAILS_ROOT'] ||= File.dirname(__FILE__) + '/../../../..'
 
 require 'test/unit'
-require File.expand_path(File.join(File.dirname(__FILE__), '../../../../config/environment.rb'))
-require 'breakpoint'
+require File.expand_path(File.join(ENV['RAILS_ROOT'], 'config/environment.rb'))
 require 'active_record/fixtures'
 require 'action_controller/test_process'
 
@@ -87,6 +87,14 @@ class Test::Unit::TestCase #:nodoc:
       end
     end
 
+    def upload_merb_file(options = {})
+      use_temp_file options[:filename] do |file|
+        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')}
+        att.reload unless att.new_record?
+        return att
+      end
+    end
+    
     def use_temp_file(fixture_filename)
       temp_path = File.join('/tmp', File.basename(fixture_filename))
       FileUtils.mkdir_p File.join(fixture_path, 'tmp')
diff --git a/vendor/plugins/attachment_fu/vendor/red_artisan/core_image/filters/color.rb b/vendor/plugins/attachment_fu/vendor/red_artisan/core_image/filters/color.rb
new file mode 100644 (file)
index 0000000..f593b90
--- /dev/null
@@ -0,0 +1,27 @@
+module RedArtisan
+  module CoreImage
+    module Filters
+      module Color
+        
+        def greyscale(color = nil, intensity = 1.00)
+          create_core_image_context(@original.extent.size.width, @original.extent.size.height)
+          
+          color = OSX::CIColor.colorWithString("1.0 1.0 1.0 1.0") unless color
+          
+          @original.color_monochrome :inputColor => color, :inputIntensity => intensity do |greyscale|
+            @target = greyscale
+          end
+        end
+        
+        def sepia(intensity = 1.00)
+          create_core_image_context(@original.extent.size.width, @original.extent.size.height)
+          
+          @original.sepia_tone :inputIntensity => intensity do |sepia|
+            @target = sepia
+          end
+        end
+        
+      end
+    end
+  end
+end
\ No newline at end of file
diff --git a/vendor/plugins/attachment_fu/vendor/red_artisan/core_image/filters/effects.rb b/vendor/plugins/attachment_fu/vendor/red_artisan/core_image/filters/effects.rb
new file mode 100644 (file)
index 0000000..2e0f244
--- /dev/null
@@ -0,0 +1,31 @@
+module RedArtisan
+  module CoreImage
+    module Filters
+      module Effects
+        
+        def spotlight(position, points_at, brightness, concentration, color)
+          create_core_image_context(@original.extent.size.width, @original.extent.size.height)
+          
+          @original.spot_light :inputLightPosition => vector3(*position), :inputLightPointsAt => vector3(*points_at), 
+                               :inputBrightness => brightness, :inputConcentration => concentration, :inputColor => color do |spot|
+            @target = spot
+          end
+        end
+        
+        def edges(intensity = 1.00)
+          create_core_image_context(@original.extent.size.width, @original.extent.size.height)
+          
+          @original.edges :inputIntensity => intensity do |edged|
+            @target = edged
+          end
+        end
+        
+        private
+        
+          def vector3(x, y, w)
+            OSX::CIVector.vectorWithX_Y_Z(x, y, w)
+          end
+      end
+    end
+  end
+end
diff --git a/vendor/plugins/attachment_fu/vendor/red_artisan/core_image/filters/perspective.rb b/vendor/plugins/attachment_fu/vendor/red_artisan/core_image/filters/perspective.rb
new file mode 100644 (file)
index 0000000..6160dd8
--- /dev/null
@@ -0,0 +1,25 @@
+module RedArtisan
+  module CoreImage
+    module Filters
+      module Perspective
+        
+        def perspective(top_left, top_right, bottom_left, bottom_right)
+          create_core_image_context(@original.extent.size.width, @original.extent.size.height)
+          
+          @original.perspective_transform :inputTopLeft => top_left, :inputTopRight => top_right, :inputBottomLeft => bottom_left, :inputBottomRight => bottom_right do |transformed|
+            @target = transformed
+          end
+        end
+
+        def perspective_tiled(top_left, top_right, bottom_left, bottom_right)
+          create_core_image_context(@original.extent.size.width, @original.extent.size.height)
+          
+          @original.perspective_tile :inputTopLeft => top_left, :inputTopRight => top_right, :inputBottomLeft => bottom_left, :inputBottomRight => bottom_right do |tiled|
+            @target = tiled
+          end
+        end
+        
+      end
+    end
+  end
+end
\ No newline at end of file
diff --git a/vendor/plugins/attachment_fu/vendor/red_artisan/core_image/filters/quality.rb b/vendor/plugins/attachment_fu/vendor/red_artisan/core_image/filters/quality.rb
new file mode 100644 (file)
index 0000000..018690f
--- /dev/null
@@ -0,0 +1,25 @@
+module RedArtisan
+  module CoreImage
+    module Filters
+      module Quality
+        
+        def reduce_noise(level = 0.02, sharpness = 0.4)
+          create_core_image_context(@original.extent.size.width, @original.extent.size.height)
+          
+          @original.noise_reduction :inputNoiseLevel => level, :inputSharpness => sharpness do |noise_reduced|
+            @target = noise_reduced
+          end
+        end
+        
+        def adjust_exposure(input_ev = 0.5)
+          create_core_image_context(@original.extent.size.width, @original.extent.size.height)
+          
+          @original.exposure_adjust :inputEV => input_ev do |adjusted|
+            @target = adjusted
+          end          
+        end
+        
+      end
+    end
+  end
+end
\ No newline at end of file
diff --git a/vendor/plugins/attachment_fu/vendor/red_artisan/core_image/filters/scale.rb b/vendor/plugins/attachment_fu/vendor/red_artisan/core_image/filters/scale.rb
new file mode 100644 (file)
index 0000000..f729b59
--- /dev/null
@@ -0,0 +1,47 @@
+module RedArtisan
+  module CoreImage
+    module Filters
+      module Scale
+        
+        def resize(width, height)
+          create_core_image_context(width, height)
+
+          scale_x, scale_y = scale(width, height)
+
+          @original.affine_clamp :inputTransform => OSX::NSAffineTransform.transform do |clamped|
+            clamped.lanczos_scale_transform :inputScale => scale_x > scale_y ? scale_x : scale_y, :inputAspectRatio => scale_x / scale_y do |scaled|
+              scaled.crop :inputRectangle => vector(0, 0, width, height) do |cropped|
+                @target = cropped
+              end
+            end
+          end
+        end
+
+        def thumbnail(width, height)
+          create_core_image_context(width, height)
+
+          transform = OSX::NSAffineTransform.transform
+          transform.scaleXBy_yBy *scale(width, height)
+
+          @original.affine_transform :inputTransform => transform do |scaled|
+            @target = scaled
+          end
+        end
+
+        def fit(size)
+          original_size = @original.extent.size
+          scale = size.to_f / (original_size.width > original_size.height ? original_size.width : original_size.height)
+          resize (original_size.width * scale).to_i, (original_size.height * scale).to_i
+        end
+        
+        private
+        
+          def scale(width, height)
+            original_size = @original.extent.size
+            return width.to_f / original_size.width.to_f, height.to_f / original_size.height.to_f
+          end
+          
+      end
+    end
+  end
+end
\ No newline at end of file
diff --git a/vendor/plugins/attachment_fu/vendor/red_artisan/core_image/filters/watermark.rb b/vendor/plugins/attachment_fu/vendor/red_artisan/core_image/filters/watermark.rb
new file mode 100644 (file)
index 0000000..3c3a1ad
--- /dev/null
@@ -0,0 +1,32 @@
+module RedArtisan
+  module CoreImage
+    module Filters
+      module Watermark
+        
+        def watermark(watermark_image, tile = false, strength = 0.1)
+          create_core_image_context(@original.extent.size.width, @original.extent.size.height)
+          
+          if watermark_image.respond_to? :to_str
+            watermark_image = OSX::CIImage.from(watermark_image.to_str)
+          end
+          
+          if tile
+            tile_transform = OSX::NSAffineTransform.transform
+            tile_transform.scaleXBy_yBy 1.0, 1.0
+            
+            watermark_image.affine_tile :inputTransform => tile_transform do |tiled|
+              tiled.crop :inputRectangle => vector(0, 0, @original.extent.size.width, @original.extent.size.height) do |tiled_watermark|
+                watermark_image = tiled_watermark
+              end
+            end
+          end
+          
+          @original.dissolve_transition :inputTargetImage => watermark_image, :inputTime => strength do |watermarked|
+            @target = watermarked
+          end
+        end
+
+      end
+    end
+  end
+end
\ No newline at end of file
diff --git a/vendor/plugins/attachment_fu/vendor/red_artisan/core_image/processor.rb b/vendor/plugins/attachment_fu/vendor/red_artisan/core_image/processor.rb
new file mode 100644 (file)
index 0000000..965e70c
--- /dev/null
@@ -0,0 +1,123 @@
+require 'rubygems'
+require 'osx/cocoa'
+require 'active_support'
+
+require 'red_artisan/core_image/filters/scale'
+require 'red_artisan/core_image/filters/color'
+require 'red_artisan/core_image/filters/watermark'
+require 'red_artisan/core_image/filters/quality'
+require 'red_artisan/core_image/filters/perspective'
+require 'red_artisan/core_image/filters/effects'
+
+# Generic image processor for scaling images based on CoreImage via RubyCocoa.
+#
+# Example usage:
+#
+# p = Processor.new OSX::CIImage.from(path_to_image)
+# p.resize(640, 480)
+# p.render do |result|
+#   result.save('resized.jpg', OSX::NSJPEGFileType)
+# end
+#
+# This will resize the image to the given dimensions exactly, if you'd like to ensure that aspect ratio is preserved:
+#
+# p = Processor.new OSX::CIImage.from(path_to_image)
+# p.fit(640)
+# p.render do |result|
+#   result.save('resized.jpg', OSX::NSJPEGFileType)
+# end
+#
+# fit(size) will attempt its best to resize the image so that the longest width/height (depending on image orientation) will match
+# the given size. The second axis will be calculated automatically based on the aspect ratio.
+#
+# Scaling is performed by first clamping the image so that its external bounds become infinite, this helps when scaling so that any
+# rounding discrepencies in dimensions don't affect the resultant image. We then perform a Lanczos transform on the image which scales
+# it to the target size. We then crop the image to the traget dimensions.
+#
+# If you are generating smaller images such as thumbnails where high quality rendering isn't as important, an additional method is
+# available:
+#
+# p = Processor.new OSX::CIImage.from(path_to_image)
+# p.thumbnail(100, 100)
+# p.render do |result|
+#   result.save('resized.jpg', OSX::NSJPEGFileType)
+# end
+#
+# This will perform a straight affine transform and scale the X and Y boundaries to the requested size. Generally, this will be faster
+# than a lanczos scale transform, but with a scaling quality trade.
+#
+# More than welcome to intregrate any patches, improvements - feel free to mail me with ideas.
+#
+# Thanks to
+# * Satoshi Nakagawa for working out that OCObjWrapper needs inclusion when aliasing method_missing on existing OSX::* classes.
+# * Vasantha Crabb for general help and inspiration with Cocoa
+# * Ben Schwarz for example image data and collaboration during performance testing
+#
+# Copyright (c) Marcus Crafter <crafterm@redartisan.com> released under the MIT license
+#
+module RedArtisan
+  module CoreImage
+    class Processor
+  
+      def initialize(original)
+        if original.respond_to? :to_str
+          @original = OSX::CIImage.from(original.to_str)
+        else
+          @original = original
+        end
+      end
+  
+      def render(&block)
+        raise "unprocessed image: #{@original}" unless @target
+        block.call @target
+      end
+      
+      include Filters::Scale, Filters::Color, Filters::Watermark, Filters::Quality, Filters::Perspective, Filters::Effects
+  
+      private
+  
+        def create_core_image_context(width, height)
+               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)
+               context = OSX::NSGraphicsContext.graphicsContextWithBitmapImageRep(output)
+               OSX::NSGraphicsContext.setCurrentContext(context)
+               @ci_context = context.CIContext
+        end
+        
+        def vector(x, y, w, h)
+          OSX::CIVector.vectorWithX_Y_Z_W(x, y, w, h)
+        end
+    end
+  end
+end
+
+module OSX
+  class CIImage
+    include OCObjWrapper
+  
+    def method_missing_with_filter_processing(sym, *args, &block)
+      f = OSX::CIFilter.filterWithName("CI#{sym.to_s.camelize}")
+      return method_missing_without_filter_processing(sym, *args, &block) unless f
+    
+      f.setDefaults if f.respond_to? :setDefaults
+      f.setValue_forKey(self, 'inputImage')
+      options = args.last.is_a?(Hash) ? args.last : {}
+      options.each { |k, v| f.setValue_forKey(v, k.to_s) }
+    
+      block.call f.valueForKey('outputImage')
+    end
+  
+    alias_method_chain :method_missing, :filter_processing
+      
+    def save(target, format = OSX::NSJPEGFileType, properties = nil)
+      bitmapRep = OSX::NSBitmapImageRep.alloc.initWithCIImage(self)
+      blob = bitmapRep.representationUsingType_properties(format, properties)
+      blob.writeToFile_atomically(target, false)
+    end
+  
+    def self.from(filepath)
+      raise Errno::ENOENT, "No such file or directory - #{filepath}" unless File.exists?(filepath)
+      OSX::CIImage.imageWithContentsOfURL(OSX::NSURL.fileURLWithPath(filepath))
+    end
+  end
+end
+

Benjamin Mako Hill || Want to submit a patch?