我正在解决这些问题,并且有点坚持如何完成这个问题。这是RSPEC,特别麻烦我的是最后一个"它缩进"测试:
# # Topics
#
# * method_missing
# * blocks
# * strings
# * hashes
require "13_xml_document"
describe XmlDocument do
before do
@xml = XmlDocument.new
end
it "renders an empty tag" do
@xml.hello.should == "<hello/>"
end
it "renders a tag with attributes" do
@xml.hello(:name => 'dolly').should == "<hello name='dolly'/>"
end
it "renders a randomly named tag" do
tag_name = (1..8).map{|i| ('a'..'z').to_a[rand(26)]}.join
@xml.send(tag_name).should == "<#{tag_name}/>"
end
it "renders block with text inside" do
@xml.hello do
"dolly"
end.should == "<hello>dolly</hello>"
end
it "nests one level" do
@xml.hello do
@xml.goodbye
end.should == "<hello><goodbye/></hello>"
end
it "nests several levels" do
xml = XmlDocument.new
xml.hello do
xml.goodbye do
xml.come_back do
xml.ok_fine(:be => "that_way")
end
end
end.should == "<hello><goodbye><come_back><ok_fine be='that_way'/></come_back></goodbye></hello>"
end
it "indents" do
@xml = XmlDocument.new(true)
@xml.hello do
@xml.goodbye do
@xml.come_back do
@xml.ok_fine(:be => "that_way")
end
end
end.should ==
"<hello>\n" +
" <goodbye>\n" +
" <come_back>\n" +
" <ok_fine be='that_way'/>\n" +
" </come_back>\n" +
" </goodbye>\n" +
"</hello>\n"
end
end
我觉得我理解这个问题,解决方案就像是
"<#{method}>\n" + " #{yield}" + "</#{method}>\n"
给出我的代码:
class XmlDocument
#use method missing so that arbitrary methods
#can be called and converted to XML
def method_missing(method, hash=nil, &block)
if (hash == nil && block == nil)
"<#{method}/>"
elsif hash.is_a?(Hash)
#renders tag with attributes (from hash)
my_key = nil
my_val = nil
hash.each do |key, value|
my_key = key
my_val = value
end
"<#{method} #{my_key}='#{my_val}'/>"
else
#passes whatever to between tags including nested methods.
"<#{method}>#{yield}</#{method}>"
end
end
end
我的问题是我不知道如何区分&#34;它嵌套了几个级别&#34;测试来自&#34;它缩进&#34;测试所以我可以把它放到我的&#34; if&#34;声明。唯一可以区分它们的是&#34;它缩进&#34;测试已经
@xml = XmlDocument.new(true)
&#34; true&#34;是什么意思?作为#new的论据?它与我的问题有关吗?
答案 0 :(得分:1)
初始化时,可以将参数传递给对象。在这种情况下,您希望该值默认为false
。这样,缩进代码仅在调用XmlDocument.new(true)
时运行。
class XmlDocument
def initialize(indent = false)
@indent = indent
end
def method_missing(method, args=nil, &block)
if @indent == true
#run with indents
else
#run without indents
end
end
end