Rails 3模板:inject_into_file的奇怪行为

时间:2012-04-25 11:44:03

标签: ruby-on-rails ruby templates

我正在为Rails 3编写一个模板(你可以找到它here),而且我遇到了以下问题的麻烦:

# 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

2 个答案:

答案 0 :(得分:4)

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

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

此版本适用于我:

https://gist.github.com/2573325

不要问我为什么这个选项有意义,等等。

答案 1 :(得分:2)

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

rails docs说以这种方式使用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