Commandline Statement Inside Rails Controller

How to execute rails commandline statement inside our rails controller

eg: I need to execute this statement

$rails new test -d postgresql

from my rails controller

def index

/Code to execute the command line statement/

end

Hope am clear..

4 Answers

If you want to run shell commands inside controller just use "system"

Eg:

system "rails new test -d postgresql"

or else

exec "rails new test -d postgresql"
2

Use backticks to shell out, like this:
`rails new test -d postgresql`

It might be smarter to use a job queue for this.

To run command line statements inside controller, we can use system command

system "cd {path_to_folder}; rails new test -d postgresql"

Like PradeepKumar said (would comment on it but can't due to rep):

system "cd {path_to_folder}; rails new test -d postgresql"

You have to declare all the commands you want to run in the same instruction (separated by a ;). I wasn't doing so (separated the cd command to access the directory with my runnable and the actually execution line in two different calls) and the result I was getting was not the desired. For example, if you try to run:

system "cd {path_to_folder}"

And then:

system "rails new test -d postgresql"

The rails command wont be executed in the context of the path_to_folder but in the default location for the command line interface (for instance C:\Users\Me) or the environment of your Rails program.

Also I was getting an error on command execution which I fixed by adding a & in the end of the command. In this case that the instructions has two commands, I added it in the end of the first command (before the ;).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Chloe Bennett

Chloe Bennett

Culture, Media & Entertainment Columnist

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.

Share this article
Twitter Facebook Pinterest