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
59 self.timestamp = Time.now
61 old_segment = OldSegment.from_segment(self)
65 rescue Exception => ex
71 doc = OSM::API.new.get_xml_doc
72 doc.root << to_xml_node()
76 def to_xml_node(user_display_name_cache = nil)
77 el1 = XML::Node.new 'segment'
78 el1['id'] = self.id.to_s
79 el1['from'] = self.node_a.to_s
80 el1['to'] = self.node_b.to_s
82 user_display_name_cache = {} if user_display_name_cache.nil?
84 if user_display_name_cache and user_display_name_cache[self.user_id]
85 # use the cache if available
86 elsif self.user.data_public?
87 user_display_name_cache[self.user_id] = self.user.display_name
89 user_display_name_cache[self.user_id] = nil
92 el1['user'] = user_display_name_cache[self.user_id] unless user_display_name_cache[self.user_id].nil?
94 Segment.split_tags(el1, self.tags)
95 el1['visible'] = self.visible.to_s
96 el1['timestamp'] = self.timestamp.xmlschema
100 def self.split_tags(el, tags)
101 tags.split(';').each do |tag|
102 parts = tag.split('=')
105 key = parts[0].strip unless parts[0].nil?
106 val = parts[1].strip unless parts[1].nil?
107 if key != '' && val != ''
108 el2 = XML::Node.new('tag')
116 def preconditions_ok?
117 from_node and from_node.visible and to_node and to_node.visible