I'm still pretty new at Ruby, but my coworker and all-around good guy Derek Schaefer pointed this tip out to me when reviewing a recent pull request of mine.

Context

I am trying to show a visual element side-by-side with a corresponding CSS code snippet. Using rouge, I apply syntax highlighting to a plain text code sample.

Visual Element

Before

My first approach was ugly. It looked something like this:

<!-- view.html.erb -->
<section class="code-sample">
  <div class="container">
<%= highlight(
'.example {
  color: $example-color;
}',
'scss'
)%>
  </div>
</section>
# helper.rb
def highlight(language, code)
  Rouge.highlight(code, language.downcase, 'html').html_safe
end

Notice how I had to break the indentation in the markup, and how ugly the arguments look. It was a pain in the neck to write (particularly in my auto-indenting vim setup), and is not pleasant to look at.

After

There is a better way! The &block keyword allows you to capture a blob of ruby code as a string, resulting in a much prettier way of handling complex content. Observe:

<!-- view.html.erb -->
<section class="code-sample">
  <div class="container">
    <%= highlight 'scss' do %>
      .example {
        color: $example-color;
      }
    <% end %>
  </div>
</section>
# helper.rb
def highlight(language, &amp;block)
  code = capture(&amp;block).strip_heredoc.strip
  Rouge.highlight(code, language.downcase, 'html').html_safe
end

This approach is much more intuitive and nicer-looking. Thanks to Derek for a great tip. For a more in-depth look at blocks and their general use in ruby, this Stack Overflow thread had some good information.

Keep the conversation going

Anything to add? Tweet me @jbones3000!