Rails helpers. Rediscovered

Normally, you’d use partials to manage some common functionality in a single file. For example like this:

Somewhere in your view:

<%= render :partial => 'ads/ad', :locals => {:placement => 'frontpage-banner1'} %>

It’s quite concise, but how about making it even less verbose? Helpers to the rescue:

module AdsHelper
  def ad(placement)
    render :partial => 'ads/ad', :locals => {:placement => placement}
  end
end

And now you can write this in your view:

<%= ad 'frontpage-banner1' %>

Nice! I believe it’s as short as it gets. Sure, if you render this partial only a few times it might not be worth it, but what if you render it 20 or 30 times?

Published by

Paweł Gościcki

Ruby/Rails programmer.