Diffy
Diffy

Reputation: 735

Call a ruby script from within a rails app controller

I'm very new to rails and I have a script that I run from the console like this

   $ ruby axml2xml.rb ExamPaper.apk

Now, how do I call this script from within my controller method and pass the same parameter as ExamPaper.apk?

I tried require 'axml2xml.rb' but got some error pointing to this line of code Zip::ZipFile.foreach(ARGV[0]) do |f|. So basically, how do I make something like axml2xml.rb 'ExamPaper.apk' in my controller?

Upvotes: 2

Views: 5366

Answers (4)

toashd
toashd

Reputation: 1002

You can try using system or popen, but only for short tasks, for more information about that, please see here.

If your task is more time consuming you definitely should have a look at something like delayed_job and use a background job or some sort of queue to run your job. This way your server doesn't get blocked and your users do not have to wait til your job completes.

Upvotes: 1

Dty
Dty

Reputation: 12273

In ruby there are several ways to run shell commands.

system("ls")
%x("ls")
`ls`   #nice they are back ticks
exec "ls"

But I'm not sure about the permissions necessary for running commands like that via rails.

Upvotes: 0

Simone Carletti
Simone Carletti

Reputation: 176352

You have at least 3 options:

  • exec(command)
  • %x{ command }
  • system(command)

They have different behaviors, so make sure to read this quicktip and/or the answer of this question to learn more about these commands.

In your case, the backticks or %x command is probably the best option.

value = `ruby axml2xml.rb ExamPaper.apk`

Upvotes: 5

Wawa Loo
Wawa Loo

Reputation: 2276

If you want to execute it as a shell command, use:

exec 'ruby axml2xml.rb ExamPaper.apk'

Upvotes: 0

Related Questions