Snippets
A patch for the GNU find tool that allows to find files etc. by their absolute access/change/modification time and date.
My XML-writing requirements are pretty modest and I really don't need a DOM or any other frills. So here's an easy way to generate XML in Ruby.
class XML
def initialize(out = STDOUT)
@out = out
@indentLvl = 0
end
def header(encoding = 'iso-8859-1')
pr "<?xml version=\"1.0\" encoding=\"#{encoding}\"?>\n"
end
def method_missing(id, *args)
attribs = {}
content = ''
arg = args.shift
unless arg.nil?
if arg.kind_of?(Hash)
attribs = arg
arg = args.shift
end
end
unless arg.nil?
content = arg.to_s.strip
end
prind "<#{id.id2name}"
attribs.each() do |k,v|
pr " #{k}='#{v}'"
end
if block_given? || !content.empty?
pr ">\n"
@indentLvl += 1
prind content, "\n" unless content.empty?
yield if block_given?
@indentLvl -= 1
prind "</#{id.id2name}>\n"
else
pr "/>\n"
end
end
def pr(*s)
@out.print s
end
def prind(*s)
@out.print ' ' * @indentLvl, s
end
end
if __FILE__ == $0
xml = XML.new
xml.header
xml.root({:a1 => 'v1', :a2 => 'v2'}) {
xml.title("Just an example")
xml.child({:a => 'v'}) {
xml.empty
}
}
end
Running the script produces the following output
<?xml version="1.0" encoding="iso-8859-1"?>
<root a1='v1' a2='v2'>
<title>
Just an example
</title>
<child a='v'>
<empty/>
</child>
</root>
|
|