在 Ruby 脚本中更改目录?

我想创建一个新的 Rails 应用程序,并启动该应用程序的 Rails 服务器,从 Ruby 脚本开始。

我的代码是这样的:

#!/usr/bin/env ruby
system "rails new my_app"
system "cd my_app"
system "rails server &"

但是,当运行“ Rails server &”时,路径不在 my _ app 文件夹中,而是在父文件夹中。

有没有一种方法来改变目录内的脚本,使我可以运行“轨道服务器”,“耙关于”和“耙数据库: 迁移”的新应用程序?

所有与小费相关的工作都会很感激。

75924 次浏览

Use Dir.chdir:

Dir.chdir "my_app"

Use Dir.chdir to change the working directory for a script.

Use Dir.chdir("[aString]")

Don't listen to them, Dir.chdir("dir") will probably do the wrong thing. What you almost always want is to limit change to a particular context, without affecting the rest of the program like this:

#!/usr/bin/env ruby
system "rails new my_app"
Dir.chdir("my_app") do
system "rails server &"
end
# back where we were, even with exception or whatever

Why can't you just do it like this:

#!/usr/bin/env ruby
system 'rails new myapp && cd myapp && rails server &'

The following lines have the same output:

puts Dir.chdir("/tmp") { IO.popen("ls -la") { |io| io.read } }


puts IO.popen(["ls", "-la", "/tmp"]).read


puts IO.popen("ls -la /tmp").read


# drwxrwxrwt 25 root       root       16384 июля  23 01:17 .
# drwxr-xr-x 22 root       root        4096 июля  22 13:36 ..
# drwxrwxr-x 12 itsnikolay itsnikolay  4096 июля  19 17:14 app_template
# drwx------  2 itsnikolay itsnikolay  4096 июля  21 15:04 .com.google.Chrome.dThb8f
# drwx------  2 itsnikolay itsnikolay  4096 июля  18 20:55 .com.google.Chrome.FGDBGc

also you can run rails and create an application (this can be helpful in rspec tests and etc.):

IO.popen("cd /tmp/ && rails new test_app").read

and ever you can run a rails server ;)

system supports :chdir argument that allows you to specify its working directory:

system("echo Test; pwd", chdir: '/tmp')

outputs '/tmp'