How do I use nested blocks passed to a method? (metaprogramming?)
Hi guys! So i am totally lost with something: I need a class that creates a pseudo xml output (only nodes). This class has a builder method (a class level method) which receives a block, and according to the block it generates an output.
For example:
XmlBuilder.build { |doc| doc.my_node "2" }
returns this string:
<my_node>2</my_node>
and
DocumentBuilder.build do |doc|
doc.outer_node do |outer_node_builder|
outer_node_builder.inner "2"
end
end
returns
<outer_node><inner> 2</inner></outer_node>
I think I should override method_missing to get the name of the method (in the 1st example wuold be "my_node" and the args ("2" in the same example), but I cannot do override it.
And more important, I have no idea how to loop through the "nested" block in example 2.
If anyone has a clue, I would really appreciate your insight.
Oh, my class is written like this:
class DocumentBuilder
def self.build
if block_given?
yield
else
"A block should be passed to the builder"
end
end
def method_missing(m, *args, &block)
puts "override method missing"
puts m
puts args
puts block
end
end