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

瘦欲@ 提交于 2019-11-27 23:42:30

问题


I'm trying out Builder::XMLMarkup to build some xml and it keeps adding an empty element to my xml.

Why does it do this and how do I stop it?

xml = Builder::XmlMarkup.new
=> <inspect/> 

回答1:


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.




回答2:


If you still want to see the output:

xml = Builder::XmlMarkup.new; xml.target!


来源:https://stackoverflow.com/questions/11971225/why-does-ruby-builderxmlmarkup-add-inspect-tag-to-xml

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!