Thursday, October 23, 2014

Yielding Haml block will return 0 (zero)

I had a presenter-view code like this one:
class MyPresenter
  def render_content
    view_header = true
    yield(self, view_header)
  end

  def tlt(name)
    "fetching translation for #{name}"
  end
end
- language_presenter = MyPresenter.new
- language_presenter.render_content do |presenter, view_header|
  = content_tag :h2, presenter.tlt('top_header') if view_header
  = presenter.tlt('main_body')
  bla bla bla 
but for some reason the value of yield(self, view_header) was 0. Not nil, not empty string but a zero.
It turns out it was caused by the way how Haml outputs to the template. Long story short, using capture_haml will capture Haml to sting, and if you render that string with =  that will make it work properly:
- language_presenter = MyPresenter.new
= language_presenter.render_content do |presenter, view_header|
  - capture_haml do
    = content_tag :h2, presenter.tlt('top_header') if view_header
    = presenter.tlt('main_body')
    bla bla bla
source: