Sha256: a83108bd2d6b03006c37cb2e9050f97ed836fa5dd497b63bdb951adf4f21e73d

Contents?: true

Size: 1.57 KB

Versions: 3

Compression:

Stored size: 1.57 KB

Contents

require 'filemagic'

module FileMagic::Ext

  def self.included(base)
    base.class_eval {
      extend ClassMethods
      include InstanceMethods
    }
  end

  module ClassMethods

    def file_type(file, *flags)
      raise NotImplementedError, 'must be implemented by including class'
    end

    def file(file, *flags)
      file_type(file, *flags)
    end

    def mime_type(file, *flags)
      flags.unshift :mime
      file_type(file, *flags)
    end

    alias_method :mime, :mime_type

    def content_type(file, *flags)
      flags << { :simplified => true }
      mime_type(file, *flags)
    end

  end

  module InstanceMethods

    def file_type(*flags)
      self.class.file_type(self, *flags)
    end

    alias_method :file, :file_type

    def mime_type(*flags)
      self.class.mime_type(self, *flags)
    end

    alias_method :mime, :mime_type

    def content_type(*flags)
      self.class.content_type(self, *flags)
    end

  end

end

class File

  include FileMagic::Ext

  def self.file_type(file, *flags)
    FileMagic.fm(*flags).file(file.respond_to?(:path) ? file.path : file)
  rescue FileMagic::FileMagicError
    nil
  end

end

class String

  include FileMagic::Ext

  def self.file_type(string, *flags)
    FileMagic.fm(*flags).buffer(string)
  rescue FileMagic::FileMagicError
    nil
  end

end

if $0 == __FILE__
  f = __FILE__
  p f

  p File.file_type(f)
  p File.mime_type(f)
  p File.content_type(f)

  f = File.new(f)
  p f

  p f.file_type
  p f.mime_type
  p f.content_type

  s = '#! /usr/bin/ruby'
  p s

  p s.file_type
  p s.mime_type
  p s.content_type
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
ruby-filemagic-0.4.2 lib/filemagic/ext.rb
ruby-filemagic-0.4.1 lib/filemagic/ext.rb
ruby-filemagic-0.4.0 lib/filemagic/ext.rb