Ruby/Rails: pass arguments to command line application from rake task
-
02-07-2021 - |
Question
How do you pass arguments from within a rake task and execute a command-line application from Ruby/Rails?
Specifically I'm trying to use pdftk (I can't find a comparable gem) to split some PDFs into individual pages. Args I'd like to pass are within < >
below:
$ pdftk <filename.pdf> burst output <filename_%04d.pdf>
Solution
In the ruby code for your rake task:
`pdftk #{input_filename} burst output #{output_filename}`
You could also do:
system("pdftk #{input_filename} burst output #{output_filename}")
system()
just returns true or false. backticks or %x()
returns whatever output the system call generates. Usually backticks are preferred, but if you don't care, then you could use system()
. I always use backticks because it's more concise.
More info here: http://rubyquicktips.com/post/5862861056/execute-shell-commands
OTHER TIPS
e.g. as:
filename = 'filename.pdf'
filename_out = 'filename_%04d.pdf'
`pdftk #{filename} burst output #{filename_out}`
or
system("pdftk #{filename} burst output #{filename_out}")
system
returns a retrun code, the backtick-version return STDOUT.
If you need stdout and stderr, you may also use Open3.open3
:
filename = 'filename.pdf'
filename_out = 'filename_%04d.pdf'
cmd = "pdftk #{filename} burst output #{filename_out}"
require 'open3'
Open3.popen3(cmd){ |stdin, stdout, stderr|
puts "This is STDOUT of #{cmd}:"
puts stdout.read
puts "This is STDERR of #{cmd}:"
puts stderr.read
}