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.
- Call the template kml2dot2.xml.builder
- 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
How to Write an Rspec Test for a Ruby Method That Contains "Gets.Chomp"
How to Ignore a Folder in Zeitwerk for Rails 6
Ruby on Rails Multiple Http Request at the Same Time
Unpermitted Parameters for Dynamic Forms in Rails 4
Add a CSS Class to <%= F.Submit %>
Consequences of Implementing To_Int and To_Str in Ruby
How to Determine If a String Is Numeric
How to Merge Consecutive Repeating Elements in an Array
How to Run Ruby on Rails Applications on a Windows Box
Convert a String of 0-F into a Byte Array in Ruby
Testing Routes with Subdomain Constraints Using Rspec
How to Find If Range Is Contained in an Array of Ranges
Is Systemexit a Special Kind of Exception
Adding a Background Image in Ruby on Rails 2 in CSS