2010-01-11 50 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的當前實現,這可能會在未來發生變化。