为什么Ruby Builder :: XmlMarkup将检查标记添加到xml? [英] Why does Ruby Builder::XmlMarkup add inspect tag to xml?
问题描述
我正在尝试使用Builder :: XMLMarkup构建一些xml,并且一直在向xml中添加一个空元素。
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/>
推荐答案
Builder实现了版本method_missing
会添加由方法调用名称指定的标记。
Builder implements a version of method_missing
that adds tags given by the name of the method call.
假设您正在使用irb(或rails的控制台)进行播放,irb的默认设置评估表达式(例如 Builder :: XmlMarkup.new
)时的行为是在其上调用 inspect
为了生成一个字符串显示给您。对于构建器, inspect
不是常用的红宝石 inspect
方法-落入 method_missing
并添加标签。
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
此处表达式的结果为 false
因此irb在其上调用 inspect
并仅留下构建器对象。
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
然后 xml
仍然是构建器irb检查时显示其内容的对象。您将无法创建名为 inspect
的标签(除非使用 tag!
),但这通常是小麻烦。
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.
这篇关于为什么Ruby Builder :: XmlMarkup将检查标记添加到xml?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!