We wanted something like the command file -b --mime-type but without executing this command from ruby (starting a process from ruby is expensive for our needs).
So, libmagic to the rescue! This is the lib which the file command is based on. For ruby, there is a binding in the ruby-filemagic gem, but we need to install first libmagic-dev package to let the gem install properly:
$ sudo apt-get install libmagic-dev $ sudo gem install ruby-filemagicNow we can determine mime-type like this:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'rubygems' | |
require 'filemagic' | |
fm = FileMagic.open(FileMagic::MAGIC_MIME_TYPE) | |
if fm | |
content_type = fm.file('/home/oleguer/musica/Portal - Still Alive.mp3') | |
fm.close | |
end |
This script will set the value "audio/mpeg" to the content_type variable.
The syntax is strange and ugly, but the param to the open method is a flag (or a ORed set of flags) that affect behaviour of other libmagic functions. As we needed only the mime type, we pass the MAGIC_MIME_TYPE flag (if not, a textual description of the file will be returned by the file function).
The rest of the flags are explained in libmagic manpage:
$ man libmagicThis was tested with Ubuntu 9.10 Karmic Koala.
No hay comentarios:
Publicar un comentario