我正在为 Rails 3 编写一个模板(你可以在这里找到它),我在以下几行方面遇到了麻烦:
# 8. config/database.yml modifications
if yes?("Do you want to set the database host to '/var/run/postgresql'?")
inject_into_file "config/database.yml", " host: /var/run/postgresqln", :after => "development:n"
# FIXME these two won't work :(((( why????
# inject_into_file "config/database.yml", " host: /var/run/postgresqln", :after => "production:n"
# inject_into_file "config/database.yml", " host: /var/run/postgresqln", :after => "test:n"
# Not finding other solutions, I rewrite the two blocks above with two seds
run %q(sed -i '/test:/a host: /var/run/postgresql' config/database.yml)
run %q(sed -i '/production:/a host: /var/run/postgresql' config/database.yml)
end
也就是说,第一个inject_to_file工作,并且在config/database.yml中我有
development:
host: /var/run/postgresql
但是其他两个inject_to_file已成功应用,但不要修改 config/database.yml!所以我有
test:
adapter: postgresql
和
production:
adapter: postgresql
您必须指定 :force => true
选项才能多次注入相同的文本。看:
http://rdoc.info/github/wycats/thor/master/Thor/Actions#insert_into_file-instance_method
这个版本对我有用:
https://gist.github.com/2573325
不要问我为什么这个选项有任何意义,呵呵。
我在这里跌跌撞撞地寻找一个稍微不同的问题的解决方案:
rails 文档说以这种方式使用inject_into_file
inject_into_file 'name_of_file.rb', after: "#The code goes below this line. Don't forget the Line break at the endn" do <<-'RUBY'
puts "Hello World"
RUBY
end
但是,这并不总是对我有用。在某些情况下,它实际上会将单词"puts"和一些 ruby 代码输出到我尝试注入的文件中。
最后我发现你可以传递一个字符串inject_into_file
这要容易得多。
inject_into_file 'name_of_file.rb', :after => "#The code goes below this line. Don't forget the Line break at the endn" do
"Hello World"
end