Commandline statement inside rails controller

半城伤御伤魂 提交于 2019-12-10 16:55:34

问题


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..


回答1:


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.




回答3:


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

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



回答4:


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 ;).



来源:https://stackoverflow.com/questions/11948192/commandline-statement-inside-rails-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!