2010-01-11 44 views
2

我做一个Rails模板文件下面介绍:阅读在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__被poiting到应用程序的根目录或其他地方。

有没有加载文件中轨模板的方法吗?

+0

看着这篇文章,我看不到任何接近这个的东西,你究竟想在这里实现什么?从单独的文件加载到样式表中?为什么你需要加载样式表?它不能直接传递给浏览器吗? – glenatron 2010-01-11 11:29:10

+0

我正在制作我自己的自定义导轨模板。我正在尝试将SASS文件加载到使用模板生成的新应用程序中。 – 2010-01-11 11:58:17

回答

3

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

正如您怀疑问题在于使用__FILE__。原因是,如果你在轨-2.3.4看\ LIB \ rails_generator \ \发电机应用\程序\ 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 

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

好消息是,传递到load_template(包含模板路径)的template参数是调用instance_eval时的局部变量,因此可以从模板中的代码中获得。相反,如果你只是做:

File.dirname(template) 

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