Snippets

Finding by absolute date & time with find

A patch for the GNU find tool that allows to find files etc. by their absolute access/change/modification time and date.

find . -mdate 2004-02-20

matches the entire day from 2004-02-20T00:00:00 to 2004-02-20T23:59:59

find . -mdate 2004-02

matches the entire month

find . -mdate 2004-02-20T20

matches from 2004-02-20T20:00:00 to 2004-02-20T20:59:59

find . -mdate -2004-02-20 -mdate +2004-02-27

matches from 2004-02-20T00:00:00 to 2004-02-26T23:59:59 -- i.e., the '+' prefix signifies an exclusive upper bound

Writing XML in Ruby

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>