Class: F1Results::Agent

Inherits:
Mechanize
  • Object
show all
Defined in:
lib/f1results/agent.rb

Instance Method Summary collapse

Instance Method Details

#get_event(season, country, type) ⇒ Object



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
# File 'lib/f1results/agent.rb', line 5

def get_event(season, country, type)
  event = Event.new(:season => season, :type => type)

  begin
    get(::File.join(F1Results::BASEURL, "results/season/#{season}/"))
  rescue Mechanize::ResponseCodeError, 404
    raise "No results for season: #{season}"
  end

  season_country_link = case
  when country.is_a?(String)
    event.country = country
    page.link_with(:text => event.country)
  when country.is_a?(Integer)

    # Get the link to the country on the nth row

    next_page = page.parser.at_xpath("//tr[not(position()=1)][#{country}]/td[1]/a")
    event.country = next_page.text
    page.link_with(:node => next_page)
  when country == :latest

    # Get the link to the country in the last row where results are present

    next_page = page.parser.at_xpath('(//tr/td[3][node()])[last()]/../td[1]/a')
    event.country = next_page.text
    page.link_with(:node => next_page)
  end
  raise "Grand Prix not found: #{season} #{country}" if season_country_link.nil?

  click(season_country_link)
  event.grand_prix = page.parser.at_xpath('//h2').text

  if event.qualifying?
    grand_prix_link = page.link_with(:text => 'QUALIFYING') || page.link_with(:text => 'SUNDAY QUALIFYING')
    raise "No qualifying results for: #{season} #{country}" if grand_prix_link.nil?
    click(grand_prix_link)
  end

  table = page.parser.xpath('//table[contains(@class, "raceResults")]')
  raise "No results for: #{season} #{country}" if table.empty?

  event.parse_results_table(table)
  event
end