1 class Segment < ActiveRecord::Base
3 set_table_name 'current_segments'
5 validates_presence_of :user_id, :timestamp
6 validates_inclusion_of :visible, :in => [ true, false ]
7 validates_numericality_of :node_a, :node_b
9 has_many :old_segments, :foreign_key => :id
12 # using belongs_to :foreign_key = 'node_*', since if use has_one :foreign_key = 'id', segment preconditions? fails checking for segment id in node table
13 belongs_to :from_node, :class_name => 'Node', :foreign_key => 'node_a'
14 belongs_to :to_node, :class_name => 'Node', :foreign_key => 'node_b'
16 def self.from_xml(xml, create=false)
24 doc.find('//osm/segment').each do |pt|
25 segment.node_a = pt['from'].to_i
26 segment.node_b = pt['to'].to_i
30 segment.id = pt['id'].to_i
34 segment.visible = true
37 segment.timestamp = Time.now
40 segment.timestamp = Time.parse(pt['timestamp'])
46 pt.find('tag').each do |tag|
47 tags << [tag['k'],tag['v']]
50 tags = tags.collect { |k,v| "#{k}=#{v}" }.join(';')
51 tags = '' if tags.nil?
64 Segment.transaction do
65 self.timestamp = Time.now
67 old_segment = OldSegment.from_segment(self)
78 doc = OSM::API.new.get_xml_doc
79 doc.root << to_xml_node()
83 def to_xml_node(user_display_name_cache = nil)
84 el1 = XML::Node.new 'segment'
85 el1['id'] = self.id.to_s
86 el1['from'] = self.node_a.to_s
87 el1['to'] = self.node_b.to_s
89 user_display_name_cache = {} if user_display_name_cache.nil?
91 if user_display_name_cache and user_display_name_cache[self.user_id]
92 # use the cache if available
93 elsif self.user.data_public?
94 user_display_name_cache[self.user_id] = self.user.display_name
96 user_display_name_cache[self.user_id] = nil
99 el1['user'] = user_display_name_cache[self.user_id] unless user_display_name_cache[self.user_id].nil?
101 Segment.split_tags(el1, self.tags)
102 el1['visible'] = self.visible.to_s
103 el1['timestamp'] = self.timestamp.xmlschema
107 def self.split_tags(el, tags)
108 tags.split(';').each do |tag|
109 parts = tag.split('=')
112 key = parts[0].strip unless parts[0].nil?
113 val = parts[1].strip unless parts[1].nil?
114 if key != '' && val != ''
115 el2 = XML::Node.new('tag')
123 def preconditions_ok?
124 from_node and from_node.visible and to_node and to_node.visible