modifying snippets of erb during processing

Today we ran into an interesting problem that turned out to have an elegant solution. We had a list of links that we wanted displayed as comma separated. Long story short, the resulting output contained spaces before the commas (i.e. Dick , Mary , and Jane). We wanted to take that output and run a regex replace on it.

Turns out this is pretty easy to do in rails. We added the following to our helper file

def suppress_comma_spacing(&block)
  res = capture(&block)
  concat(res.gsub(/\s+,/m, ','), block.binding)
end

then wrapped the code whose output needed modification in a code block in the erb file (trivial example below)

<% suppress_comma_spacing do %>
 <%= link_to "Dick", user_path(dick) %> , <%= link_to "Mary", user_path(mary) %> , and <%= link_to "Jane", user_path(jane) %>
<% end %> 

The result is Dick, Mary, and Jane with the spaces before the commas stripped. Capture allows you to get the processed erb from executing the block. Pretty useful.

ninja-decorators

A couple of us at SnapMyLife were a bit surprised you couldn’t easily use around_filters outside of rails for general ruby programs, so we implemented them and put it up on github. We called the gemĀ ninja-decorators, mostly in a mocking sense that everything seems to be rockstars and cool_fu these days. To install the gem:

gem sources -a http://gems.github.com
sudo gem install haruska-ninja-decorators 

Here is a simple example:

require 'rubygems'
require 'ninja_decorators'

class NinjaClass
  include NinjaDecorators

  attr_accessor :ret

  around_filter :common_around, [:foo, :bar]

  def foo
    @ret += "foo"
  end

  def bar
    @ret += "bar"
  end

  private

  def common_around
    @ret = "common "
    yield
    @ret += " around"
  end
end

produces

irb(main):076:0> n = NinjaClass.new
=> #<NinjaClass:0x220decc>
irb(main):077:0> n.bar
=> "common bar around"
irb(main):078:0> n.foo
=> "common foo around"

We’ll add before_filter and after_filter soon.