Sinatra: using partials with xml builder
April 23, 2011 Leave a Comment
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.