Simon Kröger wrote:
Hi Miles,
interesting idea, i did a quick (proof of concept) hack:
-------------------------------------------------------------
class Xmltree
attr_accessor :childs
attr_accessor :content
attr_accessor :attributes
def initialize
self.childs =
self.attributes = {};
end
def method_missing meth, *args, &block
return attributes[args[0]] = args[1] if meth == :=
return attributes[args[0]] if meth == :
return self.content = args if meth == '='.intern
unless child = childs.assoc(meth.to_s.chomp('='))
childs << child = [meth.to_s.chomp('='), Xmltree.new]
end
return child[1] if meth.to_s[-1] != ?=
child[1].content = args
end
def to_s
childs.map do |t, c|
"""<#{t} #{c.attributes.map do |a, v|
"#{a}=\"#{v}\""
end.join(' ')}>\n#{c}</#{t}>\n"""
end.join + content.to_s + (content ? "\n" : '')
end
end
-------------------------------------------------------------
usage:
-------------------------------------------------------------
xml = Xmltree.new
xml.header.title = 'this is a demo'
xml.body.component['type'] = 'the answer'
xml.body.component = 42
puts xml
-------------------------------------------------------------
output:
-------------------------------------------------------------
<header >
<title >
this is a demo
</title>
</header>
<body >
<component type="the answer">
42
</component>
</body>
-------------------------------------------------------------
cheers
Simon
Miles Monroe:
Awesome! That is better than I ever imagined.
Back in my Perl days, I started creating a source filter to allow the
insertion of non-Perl XPath statements that worked on an implicit XML
document.
I used the source filter to first scan the code for naked XPath
statements and then built the XML document with the slightly-modified
XPath syntax. I converted the invalid non-Perl strings into valid Perl
in the source filter.
Likewise, is it possible to insert non-Ruby text in the main namespace
and then turn it into Ruby code before the rest of the script is parsed?
I guess I'm asking if it's possible to implement a source filter in
Ruby.
Thanks.
···
--
Posted via http://www.ruby-forum.com/\.