Why Does Ruby Builder::Xmlmarkup Add Inspect Tag to Xml

Why does Ruby Builder::XmlMarkup add inspect tag to xml?

Builder implements a version of method_missing that adds tags given by the name of the method call.

Assuming you are playing in irb (or rails' console), irb's default behaviour when you evaluate an expression (such as Builder::XmlMarkup.new) is to call inspect on it, in order to generate a string to show to you. In the case of builder, inspect isn't the usual ruby inspect method - it falls through to method_missing and adds the tag.

This will only happen when playing with ruby interactively. You can do stuff like

xml = Builder::XmlMarkup.new; false

Here the result of the expression is false so irb calls inspect on that and leaves your builder object alone.

It can be awkward to keep doing this continually. If you do

xml = Builder::XmlMarkup.new; false
def xml.inspect; target!; end

then xml will still be a builder object that display its content when inspected by irb. You won't be able to create tags called inspect (other than by using tag!) but that is usually a minor inconvenience.

Extra to_s/ when using builder to generate XML

You don't need to initialize an XML builder object. Just use the integrated builder template handler.

  1. Call the template kml2dot2.xml.builder
  2. Write the code directly in the view

Example

def kml2dot2
@site = Site.find(params[:id])
end

# kml2dot2.xml.builder
xml.kml("xmlns" => "http:// www.opengis.net/kml/2.2") do
xml.Placemark do
xml.name @site.mapNameFull
xml.Point do
xml.coordinates "#{@site.lat},#{@site.lng},0"
end
end
end

Adding conditional attributes with Builder::XmlMarkup

I think something like this could work:

xm = Builder::XmlMarkup.new
attributes = {}
attributes[:attribute1] = value1 if value1
attributes[:attribute2] = value2 if value2
xm.item(attributes)

If you have more than a couple of attributes I can show you a way to minimize duplication with a similar method too.



Related Topics



Leave a reply



Submit