Commit 3ab2204b by Daniel Mendler

Merge pull request #7 from iangreenleaf/file_objects

Handle several types of file objects
parents 27a99b36 699cede5
...@@ -79,7 +79,8 @@ class MimeMagic ...@@ -79,7 +79,8 @@ class MimeMagic
# This is a slow operation. # This is a slow operation.
def self.by_magic(io) def self.by_magic(io)
if !(io.respond_to?(:seek) && io.respond_to?(:read)) if !(io.respond_to?(:seek) && io.respond_to?(:read))
io = StringIO.new(io.to_s, 'rb:binary') str = io.respond_to?(:read) ? io.read : io.to_s
io = StringIO.new(str, 'rb:binary')
end end
mime = MAGIC.find {|type, matches| magic_match(io, matches) } mime = MAGIC.find {|type, matches| magic_match(io, matches) }
mime && new(mime[0]) mime && new(mime[0])
......
...@@ -82,4 +82,20 @@ describe 'MimeMagic' do ...@@ -82,4 +82,20 @@ describe 'MimeMagic' do
MimeMagic.by_magic('Y MAGICTEST').should.equal 'application/mimemagic-test' MimeMagic.by_magic('Y MAGICTEST').should.equal 'application/mimemagic-test'
MimeMagic.by_magic('Z MAGICTEST').should.equal nil MimeMagic.by_magic('Z MAGICTEST').should.equal nil
end end
it 'should handle different file objects' do
MimeMagic.add('application/mimemagic-test', :magic => [[0, 'MAGICTEST']])
class ReadableObj
def read
'MAGICTEST'
end
end
MimeMagic.by_magic(ReadableObj.new).should.equal 'application/mimemagic-test'
class StringableObject
def to_s
'MAGICTEST'
end
end
MimeMagic.by_magic(StringableObject.new).should.equal 'application/mimemagic-test'
end
end end
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