Module: Aocli::AdventOfCode

Defined in:
lib/aocli/advent_of_code.rb,
lib/aocli/advent_of_code/client.rb

Defined Under Namespace

Classes: Client, Response

Constant Summary collapse

MAX_RETRY_COUNT =
5

Class Method Summary collapse

Class Method Details

.clientObject



23
24
25
# File 'lib/aocli/advent_of_code.rb', line 23

def client
  @client ||= Aocli::AdventOfCode::Client.new
end

.extract_text(response) ⇒ Object



57
58
59
60
61
62
# File 'lib/aocli/advent_of_code.rb', line 57

def extract_text(response)
  html = Nokogiri::HTML(response.body)
  article = html.css("article").first
  article.search("p,h2").each { |element| element.after("\n") }
  article.text
end

.fetch_description(year:, day:) ⇒ Object

Raises:

  • (StandardError)


40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/aocli/advent_of_code.rb', line 40

def fetch_description(year:, day:)
  response = nil
  attempt_count = 0
  while attempt_count < MAX_RETRY_COUNT
    attempt_count += 1
    print("\rFetching problem and input attempt ##{attempt_count}".ljust(40, " "))
    response = client.get_problem_description(year: year, day: day)
    break unless response.should_retry?

    sleep(1)
  end
  puts
  raise(StandardError, "Unable to fetch todays problem: #{response.inspect}") unless response.ok?

  response
end

.get_problem_description(year:, day:) ⇒ Object



8
9
10
11
12
# File 'lib/aocli/advent_of_code.rb', line 8

def get_problem_description(year:, day:)
  wait_for_start(year: year, day: day)
  response = fetch_description(year: year, day: day)
  extract_text(response)
end

.get_problem_inputs(year:, day:) ⇒ Object



14
15
16
17
18
19
20
21
# File 'lib/aocli/advent_of_code.rb', line 14

def get_problem_inputs(year:, day:)
  response = client.get_problem_inputs(year: year, day: day)
  unless response.ok?
    raise(StandardError, "unable to fetch input - #{response.inspect}")
  end

  response.body
end

.wait_for_start(day:, year:) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/aocli/advent_of_code.rb', line 27

def wait_for_start(day:, year:)
  while true
    current_time = DateTime.now.new_offset("EST")
    live_time = DateTime.new(year, 12, day, 0, 0, 0, "EST")
    time_to_wait = ((live_time - current_time) * 24 * 60 * 60).to_i
    break if time_to_wait < 1

    print("\rWaiting #{time_to_wait} seconds before fetching...".ljust(40, " "))
    sleep(1)
  end
  puts
end