Class: FileTypeDetector::Extension

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

Constant Summary collapse

JPG_VALID_SIG =
'ffd8ffe0'
JPG_VALID_SIG_EXIF =
'ffd8ffe1'
PNG_VALID_SIG =
'89504e470d0a1a0a'

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(file) ⇒ Extension

Returns a new instance of Extension.



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

def initialize(file)
  @file = file
end

Class Method Details

.extension(path_or_file_object) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/file_type_detector.rb', line 10

def self.extension(path_or_file_object)
  if path_or_file_object.is_a?(File) || path_or_file_object.is_a?(Tempfile)
    extension = new(path_or_file_object).detect
    path_or_file_object.close
    extension
  elsif !path_or_file_object.bytes.include?(0) && File.exist?(path_or_file_object)
    file = File.open(path_or_file_object, 'r')
    extension(file)
  elsif path_or_file_object.is_a?(String)
    file = Tempfile.new('temp')
    file.write(path_or_file_object)
    file.rewind
    ext = extension(file)
    file.unlink
    ext
  else
    raise "Expecting a file object or path to a file"
  end
end

Instance Method Details

#detectObject



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

def detect
  sig = @file.readpartial(20).unpack("H*").first
  if sig.match(JPG_VALID_SIG)
   '.jpg'
  elsif sig.match(PNG_VALID_SIG)
    '.png'
  else
    raise "Unsupported file type"
  end
end