Execute a system command in Ruby with output redirection and complex options

81 views Asked by At

I am trying to generate a thumbnail file for a PDF using Poppler. My naive solution looks like this:

`pdftoppm -jpeg -jpegopt "quality=80,progressive=y,optimize=y" -singlefile -scale-to #{size} #{input_filename} > #{output_filename}`

I'd like to mitigate command injection possibilities, which I know can be done by invoking system(cmd, *args) but this doesn't play nicely with output redirection.

I've played around with Open3 but struggling to find an example online I can use as a starting point.

1

There are 1 answers

0
griswoldbar On

It turns out my main problem here was how I was dividing up options and their arguments. Each needs to be its own argument to Open3. The following works:

status = Open3.popen2('pdftoppm', '-jpeg', '-jpegopt', 'quality=80,progressive=y,optimize=y', '-scale-to', size.to_s, '-singlefile', pathname) do |_i, o, s|
  File.open(sized_pathname(size), 'w') { |file| file.write(o.read) }
  s.value
end