-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrain.rb
More file actions
120 lines (93 loc) · 2.23 KB
/
train.rb
File metadata and controls
120 lines (93 loc) · 2.23 KB
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
class Train
extend Accessors
include InstanceCounter
include Manufacturer
include Validation
NUMBER_FORMAT = /^[a-z0-9]{3}\-?[a-z0-9]{2}$/i
attr_reader :number, :speed, :train_type, :wagons, :route, :station_index
strong_attr_accessor :number, Integer
strong_attr_accessor :speed, Integer
strong_attr_accessor :route, Route
validate :train_type, :presence
@@trains = {}
def self.find(number)
@@trains[number]
end
def self.all
@@trains
end
def initialize(number, type)
@number = number
@train_type = type
validate!
@wagons = []
@speed = init_speed
@@trains[number] = self
register_instance
end
def gain_speed(value)
@speed += value
end
def reset_speed(value)
@speed = value < @speed ? @speed -= value : 0
end
def attach_wagon(wagon)
@wagons << wagon if stopped?
end
def detach_wagon(wagon)
@wagons.delete(wagon) if stopped? && !@wagons.empty?
end
def route=(route)
@route = route
@station_index = source_station_index
current_station.take_train(self)
end
def current_station
route.stations[@station_index]
end
def next_station
route.stations[@station_index + 1] unless last_station?
end
def previous_station
route.stations[@station_index - 1] unless first_station?
end
def forward
return unless next_station
current_station.send_train(self)
next_station.take_train(self)
@station_index += 1
end
def backward
return unless previous_station
current_station.send_train(self)
previous_station.take_train(self)
@station_index -= 1
end
def cargo?
@train_type == :cargo
end
def passenger?
@train_type == :passenger
end
def each_wagons
@wagons.each_with_index { |w, i| yield w, i }
end
# ниже, все методы являются помошниками для публичных методов.
# они так же используются в подклассах, поэтому protected
protected
def init_speed
0
end
def source_station_index
0
end
def stopped?
@speed.zero?
end
def first_station?
current_station == route.stations.first
end
def last_station?
current_station == route.stations.last
end
end