From 287467de5939e02cc03329914a6d036704d641b9 Mon Sep 17 00:00:00 2001 From: Doug Fales Date: Tue, 13 Oct 2009 00:19:29 +0000 Subject: [PATCH] Adding the ability to write GPX to a string in addition to a file. Thanks to Douglas Robertson for the patch. --- lib/gpx/gpx_file.rb | 23 +++++++++++++++++------ lib/gpx/waypoint.rb | 4 ++-- 2 files changed, 19 insertions(+), 8 deletions(-) diff --git a/lib/gpx/gpx_file.rb b/lib/gpx/gpx_file.rb index 02d29c3..4e7b035 100644 --- a/lib/gpx/gpx_file.rb +++ b/lib/gpx/gpx_file.rb @@ -205,6 +205,20 @@ module GPX # Serialize the current GPXFile to a gpx file named . # If the file does not exist, it is created. If it does exist, it is overwritten. def write(filename, update_time = true) + @time = Time.now if(@time.nil? or update_time) + @name ||= File.basename(filename) + doc = generate_xml_doc + doc.save(filename, :indent => true) + end + + def to_s(update_time = true) + @time = Time.now if(@time.nil? or update_time) + doc = generate_xml_doc + doc.to_s + end + + private + def generate_xml_doc doc = Document.new doc.root = Node.new('gpx') gpx_elem = doc.root @@ -218,10 +232,9 @@ module GPX # setup the metadata elements name_elem = Node.new('name') - name_elem << File.basename(filename) + name_elem << @name time_elem = Node.new('time') - @time = Time.now if(@time.nil? or update_time) - time_elem << @time.xmlschema + time_elem << @time.xmlschema # version 1.0 of the schema doesn't support the metadata element, so push them straight to the root 'gpx' element if (@version == '1.0') then @@ -240,11 +253,9 @@ module GPX waypoints.each { |w| gpx_elem << w.to_xml } unless waypoints.nil? routes.each { |r| gpx_elem << r.to_xml } unless routes.nil? - doc.save(filename, :indent => true) + return doc end - private - # Calculates and sets the duration attribute by subtracting the time on # the very first point from the time on the very last point. def calculate_duration diff --git a/lib/gpx/waypoint.rb b/lib/gpx/waypoint.rb index 202fe42..85b44eb 100644 --- a/lib/gpx/waypoint.rb +++ b/lib/gpx/waypoint.rb @@ -74,8 +74,8 @@ module GPX end # Converts a waypoint to a XML::Node. - def to_xml - wpt = Node.new('wpt') + def to_xml(elem_name = 'wpt') + wpt = Node.new(elem_name) wpt['lat'] = lat.to_s wpt['lon'] = lon.to_s SUB_ELEMENTS.each do |sub_element_name|