Class: MimeMagic

Inherits:
Object
  • Object
show all
Defined in:
lib/mimemagic.rb,
lib/mimemagic_tables.rb

Overview

Generated from /usr/share/mime/packages/freedesktop.org.xml

Constant Summary collapse

VERSION =
'0.1.1'

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(type) ⇒ MimeMagic

Mime type by type string



11
12
13
14
15
# File 'lib/mimemagic.rb', line 11

def initialize(type)
  @type      = type
  @mediatype = @type.split('/')[0]
  @subtype   = @type.split('/')[1]
end

Instance Attribute Details

#mediatypeObject (readonly)

Returns the value of attribute mediatype.



8
9
10
# File 'lib/mimemagic.rb', line 8

def mediatype
  @mediatype
end

#subtypeObject (readonly)

Returns the value of attribute subtype.



8
9
10
# File 'lib/mimemagic.rb', line 8

def subtype
  @subtype
end

#typeObject (readonly)

Returns the value of attribute type.



8
9
10
# File 'lib/mimemagic.rb', line 8

def type
  @type
end

Class Method Details

.add(type, extensions, parents, *magics) ⇒ Object

Add custom mime type. You have to specify the type, a string list of file extensions, a string list of parent mime types and an optional detector block for magic detection.



21
22
23
24
25
26
27
# File 'lib/mimemagic.rb', line 21

def self.add(type, extensions, parents, *magics)
  TYPES[type] = [extensions, parents, block_given? ? proc(&block) : nil]
  extensions.each do |ext|
    EXTENSIONS[ext] = type
  end
  MAGIC.unshift [type, magics] if magics
end

.by_extension(ext) ⇒ Object

Lookup mime type by file extension



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

def self.by_extension(ext)
  ext = ext.downcase
  mime = EXTENSIONS[ext] || (ext[0..0] == '.' && EXTENSIONS[ext[1..-1]])
  mime ? new(mime) : nil
end

.by_magic(content) ⇒ Object

Lookup mime type by magic content analysis That could be slow



53
54
55
56
57
# File 'lib/mimemagic.rb', line 53

def self.by_magic(content)
  io = content.respond_to?(:seek) ? content : StringIO.new(content.to_s, 'rb')
  mime = MAGIC.find {|type, matches| magic_match(io, matches) }
  mime ? new(mime[0]) : nil
end

Instance Method Details

#==(x) ⇒ Object

Allow comparison with string



65
66
67
# File 'lib/mimemagic.rb', line 65

def ==(x)
  type == x.to_s
end

#child_of?(parent) ⇒ Boolean

Returns true if type is child of parent type

Returns:

  • (Boolean)


35
36
37
# File 'lib/mimemagic.rb', line 35

def child_of?(parent)
  child?(type, parent)
end

#extensionsObject

Get string list of file extensions



40
41
42
# File 'lib/mimemagic.rb', line 40

def extensions
  TYPES.key?(type) ? TYPES[type][0] : []
end

#text?Boolean

Returns true if type is a text format

Returns:

  • (Boolean)


30
31
32
# File 'lib/mimemagic.rb', line 30

def text?
  child_of? 'text/plain'
end

#to_sObject

Return type as string



60
61
62
# File 'lib/mimemagic.rb', line 60

def to_s
  type
end