Permalink
Browse files

Add a :content_type_extension interpolation to derive a file extensio…

…n from the content type.
  • Loading branch information...
1 parent dcad54d commit fdbd7bfa1033cf597d3d23432827d57f457f8e48 @mschulkind mschulkind committed Jul 12, 2011
Showing with 49 additions and 0 deletions.
  1. +25 −0 lib/paperclip/interpolations.rb
  2. +24 −0 test/interpolations_test.rb
@@ -94,6 +94,31 @@ def extension attachment, style_name
File.extname(attachment.original_filename).gsub(/^\.+/, "")
end
+ # Returns an extension based on the content type. e.g. "jpeg" for "image/jpeg".
+ # Each mime type generally has multiple extensions associated with it, so
+ # if the extension from teh original filename is one of these extensions,
+ # that extension is used, otherwise, the first in the list is used.
+ def content_type_extension attachment, style_name
+ mime_type = MIME::Types[attachment.content_type]
+ extensions_for_mime_type = unless mime_type.empty?
+ mime_type.first.extensions
+ else
+ []
+ end
+
+ original_extension = extension(attachment, style_name)
+ if extensions_for_mime_type.include? original_extension
+ original_extension
+ elsif !extensions_for_mime_type.empty?
+ extensions_for_mime_type.first
+ else
+ # It's possible, though unlikely, that the mime type is not in the
+ # database, so just use the part after the '/' in the mime type as the
+ # extension.
+ %r{/([^/]*)$}.match(attachment.content_type)[1]
+ end
+ end
+
# Returns the id of the instance.
def id attachment, style_name
attachment.instance.id
@@ -50,6 +50,30 @@ class InterpolationsTest < Test::Unit::TestCase
assert_equal "png", Paperclip::Interpolations.extension(attachment, :style)
end
+ should "return the extension of the file based on the content type" do
+ attachment = mock
+ attachment.expects(:content_type).returns('image/jpeg')
+ interpolations = Paperclip::Interpolations
+ interpolations.expects(:extension).returns('random')
+ assert_equal "jpeg", interpolations.content_type_extension(attachment, :style)
+ end
+
+ should "return the original extension of the file if it matches a content type extension" do
+ attachment = mock
+ attachment.expects(:content_type).returns('image/jpeg')
+ interpolations = Paperclip::Interpolations
+ interpolations.expects(:extension).returns('jpe')
+ assert_equal "jpe", interpolations.content_type_extension(attachment, :style)
+ end
+
+ should "return the latter half of the content type of the extension if no match found" do
+ attachment = mock
+ attachment.expects(:content_type).at_least_once().returns('not/found')
+ interpolations = Paperclip::Interpolations
+ interpolations.expects(:extension).returns('random')
+ assert_equal "found", interpolations.content_type_extension(attachment, :style)
+ end
+
should "return the #to_param of the attachment" do
attachment = mock
attachment.expects(:to_param).returns("23-awesome")

0 comments on commit fdbd7bf

Please sign in to comment.