Ruby: How to read, maybe gzipped data from a file or STDIN?

I would like to read data from an input file or STDIN - the input can be gzipped.

For files, this can be done using Zlib :: GzipReader as follows:

require 'zlib'

ios = File.open(file, mode='r')

begin
  ios = Zlib::GzipReader.new(ios)
rescue
  ios.rewind
end

ios.each_line { |line| puts line }

However, I cannot get detection of archived data from STDIN to the right:

require 'zlib'

if STDIN.tty?
  # do nothing
else
  ios = STDIN

  begin
    ios = Zlib::GzipReader.new(ios)
  rescue
    ios.rewind
  end
end

ios.each_line { |line| puts line }

The above works with gzipped data in STDIN, but regular data leads to the following:

./test.rb:14:in `rewind': Illegal seek - <STDIN> (Errno::ESPIPE)
        from ./test.rb:14:in `rescue in <main>'
        from ./test.rb:11:in `<main>'

So, if I cannot rewind STDIN, how can I check if the data in STDIN is compressed or not?

Greetings

Martin

+3
source share
1 answer

Download data from STDIN to a temporary file and only then analyze it

require 'tempfile'

tf = Tempfile.new('tmp')

while $stdin.gets do
   tf.puts $_
end

tf.rewind
+1
source

All Articles