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?
62 def save_with_history!
63 Segment.transaction do
64 self.timestamp = Time.now
66 old_segment = OldSegment.from_segment(self)
72 doc = OSM::API.new.get_xml_doc
73 doc.root << to_xml_node()
77 def to_xml_node(user_display_name_cache = nil)
78 el1 = XML::Node.new 'segment'
79 el1['id'] = self.id.to_s
80 el1['from'] = self.node_a.to_s
81 el1['to'] = self.node_b.to_s
83 user_display_name_cache = {} if user_display_name_cache.nil?
85 if user_display_name_cache and user_display_name_cache.key?(self.user_id)
86 # use the cache if available
87 elsif self.user.data_public?
88 user_display_name_cache[self.user_id] = self.user.display_name
90 user_display_name_cache[self.user_id] = nil
93 el1['user'] = user_display_name_cache[self.user_id] unless user_display_name_cache[self.user_id].nil?
95 Segment.split_tags(el1, self.tags)
96 el1['visible'] = self.visible.to_s
97 el1['timestamp'] = self.timestamp.xmlschema
101 def self.split_tags(el, tags)
102 tags.split(';').each do |tag|
103 parts = tag.split('=')
106 key = parts[0].strip unless parts[0].nil?
107 val = parts[1].strip unless parts[1].nil?
108 if key != '' && val != ''
109 el2 = XML::Node.new('tag')
117 def preconditions_ok?
118 from_node and from_node.visible and to_node and to_node.visible