REXMLBuilder
Build XML Documents programatically with Ruby and REXML via the Builder Pattern —made possible by Ruby’s blocks.
XmlBuilder uses REXML to contruct XML documents, helping to ensure XML specification conforamcy.
Usage
x = REXMLBuilder.new favs = [ 'cake', 'jelly', 'salt' ] x.table( :width=>'100%' ) { x.tr { favs.each { |v| x.td v } } } }
You can also setup the XmlBuilder to assume an implicit self, so the explict reciever is not needed.
x = REXMLBuilder.new( :implicit ) x.table( :width=>'100%' ) { tr { td "1" ; td "2" ; td "3" } } }
Implict building is more elegant in form, but it is not as functional because it makes it more difficult to refer to external values, ie. if ‘favs’ were used as in the previous example, it would be interpreted as another tag entry, not the array.
Prepare builder.
[ show source ]
# File lib/facets/more/rexmlbuilder.rb, line 113 def initialize( *options ) # initialize options @options = (Hash === options.last ? options.pop : {} ) options.each { |o| @options[o] = true } # initialize stack @stack = [] # initialize buffer @target = builder.new( @options ) end
raw insert
[ show source ]
# File lib/facets/more/rexmlbuilder.rb, line 76 def <<( str ) r = builder.raw( str ) if Array === r r.each { |e| @target << e } else @target << r end self end
Redirection functor.
[ show source ]
# File lib/facets/more/rexmlbuilder.rb, line 91 def out( str=nil ) if str self << str else @builder_functor ||= Functor.new( &__method__(:+) ) end end
text output
[ show source ]
# File lib/facets/more/rexmlbuilder.rb, line 101 def to_s @target.to_s end
Output XML document.
[ show source ]
# File lib/facets/more/rexmlbuilder.rb, line 68 def to_s( indent=nil ) o = "" @target.write( o, indent || @options[:indent] || 0 ) o end
Creates object via builder module, stores as current and appends to buffer.
[ show source ]
# File lib/facets/more/rexmlbuilder.rb, line 151 def +( op, *args, &blk ) obj = builder.send( op, *args, &blk ) @current = obj @target << obj self end
[ show source ]
# File lib/facets/more/rexmlbuilder.rb, line 107 def builder REXMLUtil end
Reroute — Core functionality.
[ show source ]
# File lib/facets/more/rexmlbuilder.rb, line 125 def method_missing( tag, *args, &block ) tag = tag.to_s if tag[-1,1] == '?' raise ArgumentError if block_given? out.instruct( tag.chomp('?'), *args ) elsif tag[-1,1] == '!' out.declare( tag.chomp('!'), *args ) else out.element( tag, *args ) end if @current and block_given? @stack << @target @target = @current if @options[:implicit] instance_eval( &block ) else block.call end @target = @stack.pop end @target end