开发者

To change directory inside a ruby script?

开发者 https://www.devze.com 2023-01-08 19:04 出处:网络
I want to create a new rails application and fire up the rails 开发者_开发问答server for that application, everything from a ruby script.

I want to create a new rails application and fire up the rails 开发者_开发问答server for that application, everything from a ruby script.

My code look like this:

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

However, when running "rails server &" the path is not in the my_app folder, but in the parent folder.

Is there a way to change directory inside a script so that i can run "rails server", "rake about" and "rake db:migrate" for that new application?

All work around tips would be appreciated.


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


Use Dir.chdir:

Dir.chdir "my_app"


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

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

outputs '/tmp'


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


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


Use Dir.chdir("[aString]")

0

精彩评论

暂无评论...
验证码 换一张
取 消