magic icon indicating copy to clipboard operation
magic copied to clipboard

Determine file type and encoding using "magic" numbers

= magic

Ruby FFI wrapper to the "magic" library, that determines content type and encoding of files and strings. The library does three types of tests: filesystem tests, magic number tests, and language tests. The first test that succeeds causes the file type to be returned. Installation

== Installation

gem install magic --source http://gemcutter.org

=== Linux

Install magic library using your package manager, e.g.:

sudo apt-get install file

=== Mac OS

If you don’t have libmagic.1.dylib file in your system, you need to install it via port command:

sudo port install file

Or for homebrew:

brew install libmagic

Sometimes you also need to set your DYLD_FALLBACK_LIBRARY_PATH environment variable to the directory where the libmagic.1.dylib is:

export DYLD_FALLBACK_LIBRARY_PATH=/opt/local/lib

=== Windows

Install File for Windows. You also need to set your PATH environment variable to the directory where the magic1.dll is:

set PATH=C:\Program Files\GnuWin32\bin;%PATH%

It might be also required to add database option explicitly:

Magic.guess_string_mime( "Magic® File™", :database => 'C:\Program Files\GnuWin32\share\misc\magic.mgc' )

== Usage

require "magic"

Magic.guess_file_mime("public/images/rails.png")

=> "image/png; charset=binary"

Magic.guess_file_mime_encoding("public/images/rails.png")

=> "binary"

Magic.guess_file_mime_type("public/images/rails.png")

=> "image/png"

Magic.guess_string_mime("Magic® File™")

=> "text/plain; charset=utf-8"

Magic.guess_string_mime_encoding("Magic® File™")

=> "utf-8"

Magic.guess_string_mime_type("Magic® File™")

=> "text/plain"

Magic.guess(:mime_type, :database => "/etc/magic") { |db| db.buffer("Magic® File™") }

=> "text/plain"

== Links

  • {project page}[http://jah.pl/projects/magic.html]
  • gemcutter[http://gemcutter.org/gems/magic]
  • repository[http://github.com/qoobaa/magic]
  • {issue tracker}[http://github.com/qoobaa/magic/issues]
  • rdoc[http://qoobaa.github.com/magic]

== Copyright

Copyright (c) 2010 Jakub Kuźma. See LICENSE[http://github.com/qoobaa/magic/raw/master/LICENSE] for details.