2013-06-26 56 views
3

當我使用:ruby過濾器做一些簡單的東西在HAML,例如...輸出HAML內容:紅寶石濾波

:ruby 
    to = comments > max_comments ? max_comments : comments 
    (0...to).each do |i| 
    comment = data[i] 
    puts li_comment comment[0], comment[1], comment[2] 
    end 

puts語句寫入輸出到控制檯。該docs for :ruby表明它

創建任何書面向名爲haml_io一個IO對象,是輸出 到Haml的文件。

究竟怎樣才能使用的haml_io對象寫入文件HAML,而不是控制檯(覺得我需要比puts其他東西)?

回答

4

此行爲changed recently - 舊行爲(版本4.0之前)將任何寫入標準的任何內容寫入Haml文檔,但這不是線程安全的。

haml_iolocal variable that refers to an IO object that writes to the document。您的代碼重寫,使用它會是這個樣子(假設commentsmax_commentsli_comment都是早先定義):

:ruby 
    to = comments > max_comments ? max_comments : comments 
    (0...to).each do |i| 
    comment = data[i] 
    haml_io.puts li_comment comment[0], comment[1], comment[2] 
    end 

haml_io實際上是一個StringIO object所以你可以使用它的任何方法,例如haml_io.write,haml_io.putc它會將輸出重定向到您的文檔。

0

...打電話haml_io

寫入它的任何內容都會輸出到Haml文檔中。