1 class Segment < ActiveRecord::Base
3 set_table_name 'current_segments'
5 validates_numericality_of :node_a
6 validates_numericality_of :node_b
8 has_many :old_segments, :foreign_key => :id
11 # using belongs_to :foreign_key = 'node_*', since if use has_one :foreign_key = 'id', segment preconditions? fails checking for segment id in node table
12 belongs_to :from_node, :class_name => 'Node', :foreign_key => 'node_a'
13 belongs_to :to_node, :class_name => 'Node', :foreign_key => 'node_b'
15 def self.from_xml(xml, create=false)
22 doc.find('//osm/segment').each do |pt|
24 segment.node_a = pt['from'].to_i
25 segment.node_b = pt['to'].to_i
28 segment.id = pt['id'].to_i
31 segment.visible = true
34 segment.timestamp = Time.now
37 segment.timestamp = Time.parse(pt['timestamp'])
43 pt.find('tag').each do |tag|
44 tags << [tag['k'],tag['v']]
47 tags = tags.collect { |k,v| "#{k}=#{v}" }.join(';')
48 tags = '' if tags.nil?
58 Segment.transaction do
60 old_segment = OldSegment.from_segment(self)
64 rescue Exception => ex
70 doc = XML::Document.new
71 doc.encoding = 'UTF-8'
72 root = XML::Node.new 'osm'
73 root['version'] = API_VERSION
74 root['generator'] = 'OpenStreetMap server'
81 el1 = XML::Node.new 'segment'
82 el1['id'] = self.id.to_s
83 el1['from'] = self.node_a.to_s
84 el1['to'] = self.node_b.to_s
85 Segment.split_tags(el1, self.tags)
86 el1['visible'] = self.visible.to_s
87 el1['timestamp'] = self.timestamp.xmlschema
91 def self.split_tags(el, tags)
92 tags.split(';').each do |tag|
93 parts = tag.split('=')
96 key = parts[0].strip unless parts[0].nil?
97 val = parts[1].strip unless parts[1].nil?
98 if key != '' && val != ''
99 el2 = XML::Node.new('tag')
107 def preconditions_ok?
108 from_node and from_node.visible and to_node and to_node.visible