Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Haml Helpers That Return Strings

I love using Haml helpers, but over the years things have changed a bit. The old way was simply to concatenate to the buffer. Here's what I have:

def confirmation_table(field)
  # Be certain that if the user is logged in, his/her email and name show
  if field.respond_to? :user
    haml_tag('tr') {
      haml_tag('th', 'Email:')
      haml_tag('td', field.user.email)
    }
    haml_tag('tr') {      
      haml_tag('th', 'Name:')
      haml_tag('td', field.user.full_name)
    }
  else
    haml_tag('tr') {
      haml_tag('th', 'User Information:')
      haml_tag('td', 'Not specified.')
    }
  end

  field.class.columns.collect{|col| col.name}.reject{|col| 
    col =~ /_at$/ || 
    col =~ /_on$/ ||
    col =~ /_id$/ ||
    col == 'id'}.each do |col|
    haml_tag('tr') {
      haml_tag('th', ActiveSupport::Inflector::humanize(col))
      haml_tag('td', typeize(field, col))
    }
  end
end

This can, of course, be accessed in my view as simply as:

- confirmation_table(@f)

However, it makes more sense (to me) for this to return a string. I can't see how haml_capture provides the same structuring ability. Any hints?

like image 740
Steve Ross Avatar asked May 04 '11 19:05

Steve Ross


1 Answers

Wrap your haml_tag calls in capture_haml:

def confirmation_table(field)
  capture_haml do
    if field.respond_to? :user
      haml_tag(:tr) do
        haml_tag('th.email', 'Email:')
        haml_tag('td.email', field.user.email)
      end
      # ...
    end
  end
end

They'll be captured and returned by capture_haml.

like image 118
Michaël Witrant Avatar answered Sep 26 '22 15:09

Michaël Witrant