Commit 9fc74e07 by Jon Yurek

Extra checking on the content type detector

parent f407412f
module Paperclip
class ContentTypeDetector
EMPTY_TYPE = "inode/x-empty"
SENSIBLE_DEFAULT = "application/octet-stream"
def initialize(filename)
@filename = filename
end
def detect
if !match?
if blank?
SENSIBLE_DEFAULT
elsif empty?
EMPTY_TYPE
elsif !match?
type_from_file_command
elsif !multiple?
possible_types.first
......@@ -16,6 +23,14 @@ module Paperclip
private
def empty?
File.exists?(@filename) && File.size(@filename) == 0
end
def blank?
@filename.nil? || @filename.empty?
end
def possible_types
@possible_types ||= MIME::Types.type_for(@filename)
end
......@@ -37,7 +52,7 @@ module Paperclip
# On BSDs, `file` doesn't give a result code of 1 if the file doesn't exist.
type = Paperclip.run("file", "-b --mime :file", :file => @filename)
if type.match(/\(.*?\)/)
type = "application/octet-stream"
type = SENSIBLE_DEFAULT
end
type.split(/[:;\s]+/)[0]
end
......
......@@ -15,6 +15,17 @@ class ContentTypeDetectorTest < Test::Unit::TestCase
assert_equal "text/plain", Paperclip::ContentTypeDetector.new(tempfile.path).detect
end
should 'return an empty content type if the file is empty' do
tempfile = Tempfile.new("something")
tempfile.rewind
assert_equal "inode/x-empty", Paperclip::ContentTypeDetector.new(tempfile.path).detect
end
should 'return a sensible default if no filename is supplied' do
assert_equal "application/octet-stream", Paperclip::ContentTypeDetector.new('').detect
end
should 'return a sensible default if something goes wrong' do
@filename = "/path/to/something"
assert_equal "application/octet-stream", Paperclip::ContentTypeDetector.new(@filename).detect
......
......@@ -5,15 +5,14 @@ class AbstractAdapterTest < Test::Unit::TestCase
attr_accessor :original_file_name, :tempfile
def content_type
type_from_file_command
Paperclip::ContentTypeDetector.new(path).detect
end
end
context "content type from file command" do
setup do
@adapter = TestAdapter.new
@adapter.stubs(:path)
Paperclip.stubs(:run).returns("image/png\n")
@adapter.stubs(:path).returns("image.png")
end
should "return the content type without newline" do
......
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