My First Real Ruby Script

Here I present my first working Ruby script that actually does something useful. I wrote it yesterday but wanted to do some more testing before presenting it here.

The Problem: I wanted to take the geocaches from the geo-nearest script (see the geo-* scripts which I have talked about before) and put them into my GPX cache respository. geo-nearest can save it’s results as a GPX file, but it saves the sym tag for each waypoint as Geocache-type (like Geocache-found, Geocache-multi, etc.) instead of just Geocache. When I import this into my GPS, it doesn’t know what icon to use so it uses the ultra-useful Toll Booth icon. So I needed something inbetween to change all the sym values before saving into my repository.

In theory, I could have just used a sed call on the GPX file and probably have been alright. But I knew that someday that would change something that it shouldn’t. Therefore I decided to use an XML parser. And, like any good student, I’m using the language I’m trying to learn at the moment. So here is the script in question:

#!/usr/bin/ruby

require "rexml/document"
require "tempfile"

# Send an argument (like coordinates) to the geo-nearest script
gpx = REXML::Document.new `geo-nearest -f -o gpx -O -  #{ARGV[0]}`

gpx.elements.each(”//wpt/sym”) { |tag|
  tag.text = tag.text.gsub(/-.+$/,”" )
}

tf = Tempfile.new(”gpx”)
tf.puts gpx
tf.flush

## ‘addcache’ is my script that some magic before running the GPX with
## gpsbabel.  you could just call gpsbabel directly
system(”addcache #{tf.path}”)

Okay, there isn’t anything Earth-shattering here. But the part that surprised me is that changing the text using REXML was so easy. Using Python’s minidom, or any DOM interface, I would have had to find the text node and then I may not have been table to change it. I would have probably had to make a new text node, delete the old one, and then import the new one. That would have been a lot more work and slower. Instead it was all in one line.

This script would have been much more difficult for me to write without the great examples at the PLEAC-Ruby site. If you’ve never checked out the PLEAC Project, I would highly recommend you do so. And, no, it’s not just for Ruby.

Leave a Reply

You must be logged in to post a comment.