Class: NationalRail::StationList

Inherits:
Object
  • Object
show all
Defined in:
lib/national-rail/station_list.rb

Defined Under Namespace

Classes: HpricotParser

Instance Method Summary collapse

Constructor Details

#initializeStationList

Returns a new instance of StationList.


17
18
19
20
21
# File 'lib/national-rail/station_list.rb', line 17

def initialize
  @agent = Mechanize.new
  @agent.pluggable_parser.html = HpricotParser
  @coordinates_vs_code = coordinates_vs_code
end

Instance Method Details

#coordinates_vs_codeObject


38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/national-rail/station_list.rb', line 38

def coordinates_vs_code
  result = {}
  File.open(File.join(File.dirname(__FILE__), "stations.kml")) do |file|
    doc = Hpricot(file)
    (doc/"kml/Document/Folder/Folder/Placemark").each do |placemark|
      if ((placemark/"styleurl") || (placemark/"styleUrl")).inner_text == "#railStation"
        name = (placemark/"name").inner_text
        description = (placemark/"description").inner_text
        code = /summary.aspx\?T\=([A-Z]{3})\"/.match(description)[1]
        longitude, latitude = (placemark/"point/coordinates").inner_text.split(",").map(&:to_f)
        result[code] = { :name => name, :latitude => latitude, :longitude => longitude }
      end
    end
  end
  result["SFA"] = { :name => "Stratford International", :latitude => 51.5445797, :longitude => -0.0097182 }
  result["EBD"] = { :name => "Ebbsfleet International", :latitude => 51.4428002, :longitude => 0.3209516 }
  result
end

#eachObject


23
24
25
26
27
28
29
30
31
32
33
# File 'lib/national-rail/station_list.rb', line 23

def each
  @agent.get("http://www.nationalrail.co.uk/stations/codes/") do |stations_page|
    (stations_page.doc/"table:nth-child(0) tbody tr").each do |tr|
      name, code = (tr/"td").map { |td| td.inner_text.gsub(%r{\n}, " ") }
      coordinates = @coordinates_vs_code[code]
      latitude = coordinates ? coordinates[:latitude] : nil
      longitude = coordinates ? coordinates[:longitude] : nil
      yield(name, code, latitude, longitude) unless name == "DUMMY TEST"
    end
  end
end