0

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>
Meltemi
  • 37,979
  • 50
  • 195
  • 293

2 Answers2

1

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

Raphael
  • 1,701
  • 15
  • 26
  • that simple huh? thought maybe i'd have to call some library to execute a command... guess not! thanks! – Meltemi Sep 14 '12 at 21:38
  • That simple. You can get some more info here: http://rubyquicktips.com/post/5862861056/execute-shell-commands – Raphael Sep 14 '12 at 21:38
  • As an aside, I use ruby for many shell scripts because of this. I f***ing hate bash. – Raphael Sep 14 '12 at 21:39
  • no, it's a system call, ruby `require` wouldn't help. If it's not working, make sure the environment variables are set such that pdftk can be called from wherever you're invoking the rake task – Raphael Sep 14 '12 at 21:46
  • Also updated my answer w/info about `system()` if you want it. – Raphael Sep 14 '12 at 21:48
1

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
}
knut
  • 27,320
  • 6
  • 84
  • 112
  • what's that `system` function doing? that's kind of what I was expecting to have to do... pros/cons to one style over the other? – Meltemi Sep 14 '12 at 21:42
  • 1
    system() 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. – Raphael Sep 14 '12 at 21:47
  • I adapted my answer and added a solution with `Open3.popen3` to get stderr and stdout. – knut Sep 14 '12 at 22:15