Module: MagicBytes

Extended by:
MagicBytes
Included in:
MagicBytes
Defined in:
lib/magic_bytes.rb

Defined Under Namespace

Classes: FileType

Constant Summary collapse

VERSION =
'1.0.2'
HEADER_SIZE =

The maximum length supported (needed for .tar archives)

262
ReadError =

Gets raised when the file being read from is at EOF or empty (when read() from the file returns ‘nil`)

Class.new(StandardError)

Instance Method Summary collapse

Instance Method Details

#detect(header_bytes) ⇒ Hash?

This is a line-for-line port of github.com/sindresorhus/file-type which is more than sufficient for our purposes

Parameters:

  • header_bytes (String)

    the header bytes of the file

Returns:

  • (Hash, nil)

    the hash of ext: and mime: or nil if the type could not be deduced

Raises:



31
32
33
34
35
# File 'lib/magic_bytes.rb', line 31

def detect(header_bytes)
  raise ReadError unless header_bytes
  d = _detect(header_bytes)
  FileType.new(d.fetch(:ext), d.fetch(:mime))
end

#read_and_detect(io) ⇒ Hash?

Performs detection from a given IO or File.

Parameters:

  • io (#read)

    a readable object

Returns:

  • (Hash, nil)

    the hash of ext: and mime: or nil if the type could not be deduced

Raises:



20
21
22
23
24
# File 'lib/magic_bytes.rb', line 20

def read_and_detect(io)
  first_n_bytes = io.read(HEADER_SIZE)
  raise ReadError unless first_n_bytes
  detect(first_n_bytes)
end