1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
|
class StopAreaCopy
include ActiveModel::Validations
include ActiveModel::Conversion
extend ActiveModel::Naming
attr_accessor :source_id, :hierarchy, :area_type, :source, :copy
validates_presence_of :source_id, :hierarchy, :area_type
validates :hierarchy, inclusion: { in: %w(child parent) }
def initialize(attributes = {})
attributes.each { |name, value| send("#{name}=", value) } if attributes
if self.area_type.blank? && self.source != nil
self.source_id = self.source.id
if self.hierarchy == "child"
if self.source.area_type.underscore == "stop_place"
self.area_type="commercial_stop_point"
else
self.area_type="boarding_position"
end
else
if self.source.area_type.underscore == "stop_place" || self.source.area_type.underscore == "commercial_stop_point"
self.area_type="stop_place"
else
self.area_type="commercial_stop_point"
end
end
end
end
def persisted?
false
end
def source
@source ||= Chouette::StopArea.find self.source_id
end
def copy
@copy ||= self.source.duplicate
end
def copy_is_source_parent?
self.hierarchy == "parent"
end
def copy_is_source_child?
self.hierarchy == "child"
end
def copy_modfied_attributes
{ :name => self.source.name, # TODO: change ninoxe to avoid that !!!
:area_type => self.area_type.camelcase,
:registration_number => nil,
:parent_id => copy_is_source_child? ? self.source_id : nil
}
end
def source_modified_attributes
return {} unless copy_is_source_parent?
{ :parent_id => self.copy.id
}
end
def save
begin
if self.valid?
Chouette::StopArea.transaction do
copy.update_attributes copy_modfied_attributes
if copy.valid?
unless source_modified_attributes.empty?
source.update_attributes source_modified_attributes
end
true
else
copy.errors.full_messages.each do |m|
errors.add :base, m
end
false
end
end
else
false
end
rescue Exception => exception
Rails.logger.error(exception.message)
Rails.logger.error(exception.backtrace.join("\n"))
errors.add :base, I18n.t("stop_area_copies.errors.exception")
false
end
end
end
|