我正在尝试创建一个 Rails 应用程序模板,其中包含这段代码
file 'config/sass.rb', <<-RUBY
Sass::Engine::DEFAULT_OPTIONS[:load_paths].tap do |load_paths|
load_paths << "#{Rails.root}/app/assets/stylesheets"
load_paths << "#{Gem.loaded_specs['compass'].full_gem_path}/frameworks/compass/stylesheets"
end
RUBY
当我使用此模板运行“rails new”时,出现以下错误:
undefined method `root' for Rails:Module (NoMethodError)
我不熟悉应用程序模板以及此代码块语法。 (你甚至称那个 <<-RUBY block 是什么?在谷歌上搜索真的很难)。我的印象是它不会在 block 内运行任何代码,因此它不应该导致错误。给了什么?
更新:让我添加更多上下文:
我正在尝试修改此处的应用程序模板:https://github.com/leshill/rails3-app/blob/master/app.rb我想添加这篇博文中的代码:http://metaskills.net/2011/05/18/use-compass-sass-framework-files-with-the-rails-3.1-asset-pipeline/这样我就可以在 rails3.1 中获得指南针支持
最佳答案
详细说明 mu 的观点。
<<-SOMESTIRING
语法定义字符串的开头。该字符串以 SOMESTRING
结尾(行首)
比如你经常看到这个
string = <<-EOF
Hey this is a really long string
with lots of new lines
EOF
string # => " Hey this is a really long string\n\n with lots of new lines\n"
在本例中为 RUBY
是表示这是 ruby 代码(将被评估)。你必须记住,在字符串中时 #{ruby_code}
转义语法将评估给定的 ruby_code 并将结果插入到字符串中。
因此,为了解决这个问题,您可以这样做,
irb >> s = <<-RUBY
"#{'#{Rails.root}'}/app/assets/stylesheets"
RUBY
#=> ""\#{Rails.root}/app/assets/stylesheets"\n"
在这里,我们使用 #{}
断开字符串然后使用单引号告诉 ruby 我们不需要 #{Rails.root}
评估。
编辑:我在考虑更多,并意识到这是等效的并且更简洁
irb >> s= <<-RUBY
Rails.root.to_s + "/app/assets/stylesheets"
RUBY #=> "Rails.root.to_s + "/app/assets/stylesheets"\n"
这样我们就完全不用担心转义了:)
关于ruby-on-rails - Rails 应用程序模板正在运行代码并且适合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6313106/