Class: MagicShelf::FileExtractor

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#destdirObject

Returns the value of attribute destdir.



11
12
13
# File 'lib/magicshelf/fileextractor.rb', line 11

def destdir
  @destdir
end

#inputfileObject

Returns the value of attribute inputfile.



11
12
13
# File 'lib/magicshelf/fileextractor.rb', line 11

def inputfile
  @inputfile
end

Instance Method Details

#enterObject



13
14
15
16
17
18
19
20
# File 'lib/magicshelf/fileextractor.rb', line 13

def enter()
  raise MagicShelf::FileExtractorError.new("inputfile is not set") if @inputfile == nil
  mimetype = FileMagic.new(FileMagic::MAGIC_MIME_TYPE).file(@inputfile)
  raise MagicShelf::FileExtractorError.new("unsupported filetype: #{mimetype}") if not %w{application/x-rar application/zip}.include?(mimetype)
  @mimetype = mimetype
  
  yield
end

#processObject



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/magicshelf/fileextractor.rb', line 22

def process()
  case @mimetype
  when "application/zip"
    Zip::File.open(@inputfile) do |zip_file|
      zip_file.each do |entry|
        MagicShelf.logger.info("Extracting #{entry.name} ...")
        entry.extract(File.join(@destdir,entry.name))
      end
    end
  when "application/x-rar"
    out, err, status = Open3.capture3("which unrar")
    if status.exitstatus != 0
      raise MagicShelf::FileExtractorError.new("cannot execute unrar, is it on your PATH?")
    end
    
    out, err, status = Open3.capture3("unrar x #{Shellwords.escape(@inputfile)} #{Shellwords.escape(@destdir)}")
    if status.exitstatus != 0
      raise MagicShelf::FileExtractorError.new("unrar exits with status #{status.exitstatus}: \n #{out} \n #{err}")
    end
  else
    raise MagicShelf::FileExtractorError.new("no way to extract file for the file with filetype: #{@mimetype}")
  end

end