I am trying to write a class for a file parser with an class method for
opening files for reading:
class Parser
def self.open
ios = File.open(*args)
parser = self.new(ios)
if block_given?
begin
yield parser
ensure
ios.close
end
return true
else
return parser
end
end
end
This works nicely, but I would like it to work on gzipped files too.
I was thinking about checking the file type using a system call -> file.match(“gzip”) and if that is true then possibly using popen with
“|gzip -f”. But I have no idea how to get that working in this block
context?
Cheers,
Martin
possibly by detecting the file type using file - and then somehow
modify
I did look at ruby’s zlib and wondered why there is no method to check
if a file is zipped or not - one could perhaps could fix something by
rescuing the Zlib exception?
Looking at the docs there is a couple of TODOs. Perhaps this is another
one.
I did look at ruby’s zlib and wondered why there is no method to check
if a file is zipped or not - one could perhaps could fix something by
rescuing the Zlib exception?
Exactly, just try to open with GzipReader and if that throws just work
with the regular file which you have opened already.
Thanks Brian and Robert. The below snippet appears to be working nicely
though I am not sure that the file is closed if zipped?
class Parser
def self.open(*args)
ios = File.open(*args)
begin
ios = Zlib::GzipReader.new(ios)
rescue
ios.rewind
end
parse = self.new(ios)
if block_given?
begin
yield parse
ensure
ios.close
end
return true
else
return parse
end
I did look at ruby’s zlib and wondered why there is no method to check
if a file is zipped or not - one could perhaps could fix something by
rescuing the Zlib exception?
Exactly, just try to open with GzipReader and if that throws just work
with the regular file which you have opened already.
Looking at the docs there is a couple of TODOs. Perhaps this is another
one.