不過也終於解開個超級大謎團,為什麼類似
<% list_as_tree @root do |item| %>
<%= item.name %>
<%= addition_fun item %>
<% end %>
這樣的代碼能輸出內容呢。
原因很簡單,concat 魔法效果,而我就因為這個漏了這個函數浪費了近乎兩小時青春呀。
如果你使用 block.call(*p) 運行到這一步就會把運行結果輸出到erb中。
而如果使用了 capture ,他返回的是運行後的內容 而不乎自行添加到erb文件中,這時候就應該使用 concat 來輸出需要的內容了。
33: def capture(*args, &block)
34: # Return captured buffer in erb.
35: if block_called_from_erb?(block)
36: with_output_buffer { block.call(*args) }
37: else
38: # Return block result otherwise, but protect buffer also.
39: with_output_buffer { return block.call(*args) }
40: end
41: end
# Use an alternate output buffer for the duration of the block.
# Defaults to a new empty string.
def with_output_buffer(buf = '') #:nodoc:
self.output_buffer, old_buffer = buf, output_buffer
yield
output_buffer
ensure
self.output_buffer = old_buffer
end
這裡不過還是弄不清楚 block.call 的工作原理 。等自己哪天牛逼了再回頭解決