All Aboard AJAX, HTML Canvas, and the Supertrain
by Dave Hoover
|
Pages: 1, 2, 3, 4, 5, 6
I have created a local directory named docroot, which is where I'll stick my HTML. For now, I'll drop in a placeholder.
docroot/redwood.html
<html>
<body>
hello woodinville!
</body>
</html>
Now I will develop my /train/line closure in order to output something slightly more useful. I'm using JSON as the protocol between server and client because it's dead simple in JavaScript.
server.rb
...
require 'trainspotter'
...
train_spotter = TrainSpotter.new
server.mount_proc("/train/line") do |request, response|
response['Content-Type'] = "text/plain"
json = train_spotter.status_report.
map { |train| '{"track": "' + train.track.to_s + '", "location": ' + train.location.to_s + '}' }.
join ','
response.body = "[ #{json} ]"
end
...
trainspotter.rb
class TrainSpotter
def status_report
[ Status.new("south", 20) ]
end
end
class Status
attr_reader :track, :location
def initialize(track, location)
@track = track
@location = location
end
end
Pointing my browser to http://localhost:8053/train/line now yields something only slightly more useful, but it's progress:

Figure 2.
What I want is to have my TrainSpotter object act as if it contained a constantly updated status report. For now I'll implement a simplistic version of this behavior to give me some realistic data:
trainspotter.rb
TRACKS = [:north, :south]
TRAINS_PROGRESS = {:north => 5, :south => 420}
MAX_SPEED = 5
class TrainSpotter
def status_report
report = []
TRAINS_PROGRESS[:north] += rand(MAX_SPEED)
report << Status.new("north", TRAINS_PROGRESS[:north])
TRAINS_PROGRESS[:south] -= rand(MAX_SPEED)
report << Status.new("south", TRAINS_PROGRESS[:south])
end
end
...