Class: Fontist::Utils::FileMagic

Inherits:
Object
  • Object
show all
Defined in:
lib/fontist/utils/file_magic.rb

Constant Summary collapse

MAP_MAGIC_TO_TYPE =
{
  "\x00\x01\x00\x00\x00" => :ttf,
  "\x4f\x54\x54\x4f" => :otf,
  "\x74\x74\x63\x66" => :ttc,
}.freeze

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(path) ⇒ FileMagic

Returns a new instance of FileMagic.



18
19
20
# File 'lib/fontist/utils/file_magic.rb', line 18

def initialize(path)
  @path = path
end

Class Method Details

.detect(path) ⇒ Object



10
11
12
# File 'lib/fontist/utils/file_magic.rb', line 10

def self.detect(path)
  new(path).detect
end

.max_magicObject



14
15
16
# File 'lib/fontist/utils/file_magic.rb', line 14

def self.max_magic
  @max_magic ||= MAP_MAGIC_TO_TYPE.keys.map(&:bytesize).max
end

Instance Method Details

#detectObject



22
23
24
25
26
27
28
29
30
31
32
# File 'lib/fontist/utils/file_magic.rb', line 22

def detect
  beginning = File.binread(@path, self.class.max_magic)

  MAP_MAGIC_TO_TYPE.each do |magic, type|
    slice = beginning.byteslice(0, magic.bytesize)

    return type if slice == magic
  end

  nil
end