Class: TflJourneyPlanner

Inherits:
Object
  • Object
show all
Defined in:
lib/tfl_journey_planner.rb

Constant Summary collapse

JOURNEY_PLANNER_URL =
'http://m.tfl.gov.uk/mt/journeyplanner.tfl.gov.uk/user/XSLT_TRIP_REQUEST2?language=en'
JOURNEY_PLANNER_ACTION =
'/mt/journeyplanner.tfl.gov.uk/user/XSLT_TRIP_REQUEST2'

Class Method Summary collapse

Class Method Details

.get_journeys(from, to) ⇒ Object



24
25
26
27
28
29
30
31
32
# File 'lib/tfl_journey_planner.rb', line 24

def get_journeys(from, to)
  output = Nokogiri::HTML.parse(submit_form(from, to)).css('.un_space_top_bottom')
  
  routes = output.map do |route|
    process_route(route)
  end.reject(&:empty?)

  to_json(routes)
end

.has_data?(attribute) ⇒ Boolean

Returns:

  • (Boolean)


56
57
58
# File 'lib/tfl_journey_planner.rb', line 56

def has_data?(attribute) 
  !attribute.text.empty? && attribute.text.split(":").length > 1
end

.has_image?(attribute) ⇒ Boolean

Returns:

  • (Boolean)


60
61
62
# File 'lib/tfl_journey_planner.rb', line 60

def has_image?(attribute)
  !attribute.css('img').empty?
end

.images_urls(attribute) ⇒ Object



48
49
50
# File 'lib/tfl_journey_planner.rb', line 48

def images_urls(attribute)
  attribute.css('img').map{ |i| CGI.unescape(i.attr('src')).split(/\=|\&/)[1] }
end

.process_attribute(attribute) ⇒ Object



52
53
54
# File 'lib/tfl_journey_planner.rb', line 52

def process_attribute(attribute)
  "'" + attribute.text.strip.sub(": ", "': '") + "'" if has_data?(attribute)
end

.process_interchanges(attribute) ⇒ Object



44
45
46
# File 'lib/tfl_journey_planner.rb', line 44

def process_interchanges(attribute)
  attribute.text.strip + images_urls(attribute).inspect
end

.process_route(route) ⇒ Object



38
39
40
41
42
# File 'lib/tfl_journey_planner.rb', line 38

def process_route(route)
  route.css('div').map do |attribute|
    has_image?(attribute) ? process_interchanges(attribute) : process_attribute(attribute) 
  end.compact
end

.submit_form(from, to) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/tfl_journey_planner.rb', line 11

def submit_form(from, to)
  tfl = Mechanize.new

  tfl.get(JOURNEY_PLANNER_URL) do |page|
    page.form_with(:action => JOURNEY_PLANNER_ACTION) do |f|
      f.name_origin = from
      f.name_destination = to
    end.submit
  end        
  
  tfl.page.body
end

.to_json(routes) ⇒ Object



34
35
36
# File 'lib/tfl_journey_planner.rb', line 34

def to_json(routes)
  "[" + routes.map{ |r| "{" + r.join(", ") + "}" }.join(", ") + "]"
end