Sinatra: using partials with xml builder

After working mostly with Java for last few years I am back to using Ruby as a main language for my every day work. I have to say just thinking of that makes me smile :). We use Sinatra to cover our web needs and I love it.
Recently I had to generate some outbound xml feeds and wanted to reuse builder templates. Following is my take on a builder partial implementation :

module Sinatra
  module BuilderHelper
    def helper_modules
      @helper_mods ||= Sinatra::Application.ancestors.select{|m| m.name =~ /Helper/}
    end

    def builder_partial(template, xml, locals = {}, helper_mods = nil)
      template = "#{template}.builder" unless "#{template}" =~ /[.]builder$/
      helper_mods ||= self.helper_modules

      class << (context = OpenStruct.new({:xml => xml}.merge(locals))); self; end.send(:include, *helper_mods)

      File.open(File.join(settings.views, "#{template}")) do |f|
        eval f.read, context.send(:binding)
      end
    end
  end

  helpers BuilderHelper
end

As you can see, I am using OpenStruct as a context object in order to limit variable scope to the locals being passed to the partial… If you use other Sinatra helper modules and follow a naming convention, helper_mod will find it and make them available to the builder template…
This is a pretty simple helper module… but I am hoping it will save somebody time.

Advertisements

About Wondering Bear
39 years old male bear.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: