Rendering block content from erb

If you want to create any methods which returns block content and you calling this methods in erb (slim, haml, etc) — you can have a big problems. For example — you can see repetition of content in your browser or even worse.

Head tag after calling block.call in erb

Let our methods are as follows:

def add_to_head(&block)
  @head_html ||= []
  @head_html << block if block_given?
end
def display_custom_head
  return unless @head_html
  @head_html.map(&:call).join
end

You can use capture method which included to rails and sinatra-contrib librares.

But what if you can not use these methods, or they have too much overhead for a current task?

Such a case arose in my pull request in sidekiq, where I wrote a simple variant of the capture for erb files:

def capture(&block)
  block.call
  eval(‘’, block.binding)
end

I hope it will be useful. Happy hacking!

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.