XML.com: XML From the Inside Out
oreilly.comSafari Bookshelf.Conferences.

advertisement

All Aboard AJAX, HTML Canvas, and the Supertrain
by Dave Hoover | Pages: 1, 2, 3, 4, 5, 6

One final piece of functionality is needed. Train locations are just one of the possible status items that we can display. The Supertrain system also tracks "hotspots," places along the train line where there have been slowdowns or incidents. I'll begin implementing hotspots by hardcoding a few hotspot locations in the TrainSpotter, and mount a new closure on WEBrick to expose the hotspots to the web client.

server.rb

...
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

server.mount_proc("/train/hotspots") do |request, response|
  response['Content-Type'] = "text/plain"
  json = train_spotter.hot_spots
           map { |train| '{"track": "' + train.track.to_s + '", "location": ' + train.location.to_s + '}' }.
             join ','
  response.body = "[ #{json} ]"
end
...

trainspotter.rb

class TrainSpotter
...
  def hot_spots
    [ Status.new(:north, 125), Status.new(:south, 250), Status.new(:south, 150) ]
  end
end

When you look a the /train/hotspots closure, hopefully you're feeling uncomfortable. I just introduced a bunch of duplication. Let's fix that by extracting a function to convert Status objects into JSON strings.

server.rb

...
def status_list_to_json(list)
  json = list.
           map { |train| '{"track": "' + train.track.to_s + '", "location": ' + train.location.to_s + '}' }.
             join ','
  "[ #{json} ]"
end

server.mount_proc("/train/line") do |request, response|
  response['Content-Type'] = "text/plain"
  response.body = status_list_to_json(train_spotter.status_report)
end

server.mount_proc("/train/hotspots") do |request, response|
  response['Content-Type'] = "text/plain"
  response.body = status_list_to_json(train_spotter.hot_spots)
end
...

Point your browser to http://localhost:8053/train/hotspots and you'll see:

Figure 6
Figure 6.

Pages: 1, 2, 3, 4, 5, 6

Next Pagearrow