Class: Mimer

Inherits:
Object
  • Object
show all
Defined in:
lib/mimer_plus.rb

Overview

Mimer find a file’s mime-type using unix’ ‘file` command. It will never look at a file’s extension.

Basic usage:

mimer = Mimer.identify('/tmp/testfile')
=> #<Mimer:0x9f @filename="/tmp/testfile", @mime_type="image/jpeg; charset=binary">

mimer.mime_type
=> "image/jpeg; charset=binary"

mimer.text?
=> false

mimer.image?
=> true

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(filename) ⇒ Mimer

Find the mime type for filename



27
28
29
# File 'lib/mimer_plus.rb', line 27

def initialize(filename)
  @filename = filename; identify!
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(m, *args, &block) ⇒ Object

Responds to every method that ends with a question mark that isn’t implemented in Mimer



46
47
48
49
# File 'lib/mimer_plus.rb', line 46

def method_missing(m, *args, &block)
  return !! mime_type.match(/#{m.to_s.gsub(/\?$/, '')}/i) if m.to_s.match(/\?$/)
  super(m, *args, &block)
end

Instance Attribute Details

#mime_typeObject

Returns the value of attribute mime_type.



19
20
21
# File 'lib/mimer_plus.rb', line 19

def mime_type
  @mime_type
end

Class Method Details

.identify(filename) ⇒ Object

Create a new Mimer object for the specified file.



22
23
24
# File 'lib/mimer_plus.rb', line 22

def self.identify(filename)
  return !File.exists?(filename) ? nil : Mimer.new(filename)
end

Instance Method Details

#suggested_extensionObject

Suggests an extention to use like .jpg or .png



32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/mimer_plus.rb', line 32

def suggested_extension
  case(mime_type)
  when /^image\/jpeg/
    '.jpg'
  when /^image\/gif/
    '.gif'
  when /^image\/png/
    '.png'
  else
    nil
  end
end