1

我正在为 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/postgresql\n", :after => "development:\n"


  # FIXME these two won't work :(((( why????
  # inject_into_file "config/database.yml", " host: /var/run/postgresql\n", :after => "production:\n"
  # inject_into_file "config/database.yml", " host: /var/run/postgresql\n", :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
4

2 回答 2

4

您必须指定:force => true多次注入相同文本的选项。看:

http://rdoc.info/github/wycats/thor/master/Thor/Actions#insert_into_file-instance_method

这个版本适用于我:

https://gist.github.com/2573325

不要问我为什么这个选项有任何意义。

于 2012-05-02T03:18:49.080 回答
2

我在这里偶然发现了一个稍微不同的问题的解决方案:

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 end\n" 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 end\n" do
  "Hello World"
end
于 2013-05-21T17:05:52.967 回答