Commit fdbd7bfa by Matthew Schulkind

Add a :content_type_extension interpolation to derive a file extension from the content type.

parent dcad54d4
......@@ -94,6 +94,31 @@ module Paperclip
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")
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment