【问题标题】:Reading a file in Rails Template在 Rails 模板中读取文件
【发布时间】:2010-01-11 11:08:30
【问题描述】:

我正在制作如下介绍的 Rails 模板文件:

我想制作一个大文件,所以不要这样做:

file "bigfile.txt", <<-EOF
  content of the file...
EOF

我想从另一个文件中读取内容。我现在拥有的是:

file "public/stylesheets/sass/960.sass", File.read(File.expand_path(File.join(File.dirname(__FILE__), "960.sass")))

该文件与 rails 模板文件位于同一目录中。问题是:当我尝试使用模板制作 Rails 应用程序时(即rails new_app -m rails_template/rails_template.rb,我收到以下错误:

The template [rails_template/rails_template.rb] could not be loaded. Error: (eval):129:in `read': No such file or directory - /Users/myusername/Desktop/new_app/960.sass

这都是因为__SELF__ 没有按我预期的方式工作。我希望__SELF__ 是模板文件本身,但实际上,__SELF__ 指向应用程序的根目录或其他位置。

有没有办法在 Rails 模板中加载文件?

【问题讨论】:

  • 看文章我看不到任何接近这个的东西,你到底想在这里实现什么?从单独的文件中加载样式表?为什么你需要加载样式表呢?不能直接传给浏览器吗?
  • 我正在制作自己的自定义 Rails 模板。我正在尝试将 SASS 文件加载到使用模板生成的新应用中。

标签: ruby-on-rails ruby file templates


【解决方案1】:

从模板中读取文件没有问题。如果您要硬编码 960.sass 源副本的路径,那么它会正常工作。

您怀疑问题出在__FILE__ 的使用上。原因是如果你查看 rails-2.3.4\lib\rails_generator\generators\applications\app\template_runner.rb 你会看到 load_template 将模板加载到一个字符串中然后执行它使用instance_eval:

def load_template(template)
  begin
    code = open(template).read
    in_root { self.instance_eval(code) }
  rescue LoadError, Errno::ENOENT => e
    raise "The template [#{template}] could not be loaded. Error: #{e}"
    end
end

因此,当您的代码执行时,上下文是一个 eval 块,__FILE__ 不会指向您的文件。

好消息是传递给load_templatetemplate 参数(包含模板的路径)在调用instance_eval 时是一个局部变量,因此可以从模板内的代码中获得。如果你只是这样做:

File.dirname(template)

那么它应该可以工作。请注意,您随后会将代码绑定到 load_template 的当前实现,这可能会在未来发生变化。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-20
    • 1970-01-01
    • 2011-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-13
    相关资源
    最近更新 更多