Module: Sinatra::Builder

Included in:
EventContext
Defined in:
lib/codebutler/sinatra.rb

Overview

Generating conservative XML content using Builder templates.

Builder templates can be inline by passing a block to the builder method, or in external files with .builder extension by passing the name of the template to the builder method as a Symbol.

Inline Rendering

If the builder method is given a block, the block is called directly with an XmlMarkup instance and the result is returned as String:

get '/who.xml' do
  builder do |xml|
    xml.instruct!
    xml.person do
      xml.name "Francis Albert Sinatra", 
        :aka => "Frank Sinatra"
      xml.email '[email protected]'
    end
  end
end

Yields the following XML:

<?xml version='1.0' encoding='UTF-8'?>
<person>
  <name aka='Frank Sinatra'>Francis Albert Sinatra</name>
  <email>Frank Sinatra</email>
</person>

Builder Template Files

Builder templates can be stored in separate files with a .builder extension under the view path. An XmlMarkup object named xml is automatically made available to template.

Example:

get '/bio.xml' do
  builder :bio
end

The “views/bio.builder” file might contain the following:

xml.instruct! :xml, :version => '1.1'
xml.person do
  xml.name "Francis Albert Sinatra"
  xml.aka "Frank Sinatra"
  xml.aka "Ol' Blue Eyes"
  xml.aka "The Chairman of the Board"
  xml.born 'date' => '1915-12-12' do
    xml.text! "Hoboken, New Jersey, U.S.A."
  end
  xml.died 'age' => 82
end

And yields the following output:

<?xml version='1.1' encoding='UTF-8'?>
<person>
  <name>Francis Albert Sinatra</name>
  <aka>Frank Sinatra</aka>
  <aka>Ol&apos; Blue Eyes</aka>
  <aka>The Chairman of the Board</aka>
  <born date='1915-12-12'>Hoboken, New Jersey, U.S.A.</born>
  <died age='82' />
</person>

NOTE: Builder must be installed or a LoadError will be raised the first time an attempt is made to render a builder template.

See builder.rubyforge.org/ for comprehensive documentation on Builder.

Instance Method Summary collapse

Instance Method Details

#builder(content = nil, options = {}, &block) ⇒ Object



549
550
551
552
553
# File 'lib/codebutler/sinatra.rb', line 549

def builder(content=nil, options={}, &block)
  options, content = content, nil if content.is_a?(Hash)
  content = Proc.new { block } if content.nil?
  render(:builder, content, options)
end