95d8510ef03567cd7d014d4790116b0d

Hello all. I've got the following code which I'm using in a Rails helper atm. It seems there a few ways to do this so does anyone know which is the best way?

def field_row(options={}, &block)
  concat("<div class="field_row">", block.binding)
  concat(capture(&block), block.binding)
  concat("</div>", block.binding)
end

# called with something like...

<% field_row do %>
  <%= text_field blah blah blah %>
<% end %>

Refactorings

No refactoring yet !

33763c130a29de64914e684ded67f02f

Jeff Berg

November 22, 2008, November 22, 2008 17:29, permalink

1 rating. Login to rate!

That is the best way unless you are on Rails 2.2 (Which just got released). Check out this blog post: http://www.pathf.com/blogs/2008/10/rails-22-for-me-and-for-you/

def label_block(caption)
    concat("<label>")
    concat("<span>#{caption}</span>")
    yield
    concat("</label>")
  end
95d8510ef03567cd7d014d4790116b0d

Alistair

November 22, 2008, November 22, 2008 17:34, permalink

No rating. Login to rate!

That's cool thanks. I was previously using yield. What are the advantages/disadvantages of using yield over capture(&block)?

33763c130a29de64914e684ded67f02f

Jeff Berg

November 22, 2008, November 22, 2008 17:38, permalink

No rating. Login to rate!

I believe it is the same now in Rails 2.2. I am unsure how it was different before 2.2.

A8d3f35baafdaea851914b17dae9e1fc

Adam

November 24, 2008, November 24, 2008 04:38, permalink

No rating. Login to rate!
def field_row(&block)
  content_tag(:div, :class => :field_row, &block)
end
95d8510ef03567cd7d014d4790116b0d

Alistair

November 24, 2008, November 24, 2008 10:54, permalink

No rating. Login to rate!

Nice Adam. I'm ended up using the equivalent in Merb.

def row(&block)
  tag :div, capture(&block), :class => 'row'
end
55502f40dc8b7c769880b10874abc9d0

raggi

December 8, 2008, December 08, 2008 11:37, permalink

No rating. Login to rate!

<bq> That's cool thanks. I was previously using yield. What are the advantages/disadvantages of using yield over capture(&block)? </bq>

Yield does not perform any wrapping of the block into an object form (a proc), as a consequence there is a speed benefit from using yield. Some also argue that it makes the code cleaner, but I think that depends on intent.

Your refactoring





Format Copy from initial code

or Cancel