Determine file type in Ruby

Clint Pachl picture Clint Pachl · Sep 9, 2008 · Viewed 49.5k times · Source

How does one reliably determine a file's type? File extension analysis is not acceptable. There must be a rubyesque tool similar to the UNIX file(1) command?

This is regarding MIME or content type, not file system classifications, such as directory, file, or socket.

Answer

Martin Carpenter picture Martin Carpenter · May 23, 2009

There is a ruby binding to libmagic that does what you need. It is available as a gem named ruby-filemagic:

gem install ruby-filemagic

Require libmagic-dev.

The documentation seems a little thin, but this should get you started:

$ irb 
irb(main):001:0> require 'filemagic' 
=> true
irb(main):002:0> fm = FileMagic.new
=> #<FileMagic:0x7fd4afb0>
irb(main):003:0> fm.file('foo.zip') 
=> "Zip archive data, at least v2.0 to extract"
irb(main):004:0>