class RoyalMailScraper::Tracker::Request

Constants

REQUEST_URI
RETRIES_ON_ERROR
TIMEOUT

Public Instance Methods

execute() click to toggle source
# File lib/royal_mail_scraper/tracker/request.rb, line 9
def execute
  Tracker::Response.new(fetch_details_page.body)
end

Private Instance Methods

agent() click to toggle source
# File lib/royal_mail_scraper/tracker/request.rb, line 40
def agent
  @agent ||= build_agent
end
build_agent() click to toggle source
# File lib/royal_mail_scraper/tracker/request.rb, line 44
def build_agent
  agent = Mechanize.new
  agent.open_timeout = TIMEOUT
  agent.read_timeout = TIMEOUT
  agent.user_agent_alias = 'Windows Chrome'
  agent
end
fetch_details_page() click to toggle source
# File lib/royal_mail_scraper/tracker/request.rb, line 15
def fetch_details_page
  form = with_retry(RETRIES_ON_ERROR, Error) { fetch_form }

  form.tracking_number = tracking_number

  result = with_retry(RETRIES_ON_ERROR, Error) { submit_form(form) }

  result
end
fetch_form() click to toggle source
# File lib/royal_mail_scraper/tracker/request.rb, line 31
def fetch_form
  find_form(agent.get(REQUEST_URI))
end
find_form(page) click to toggle source
# File lib/royal_mail_scraper/tracker/request.rb, line 35
def find_form(page)
  page.form_with(id: 'bt-tracked-track-trace-form') ||
    raise(Error, 'Tracking code form not found')
end
submit_form(form) click to toggle source
# File lib/royal_mail_scraper/tracker/request.rb, line 25
def submit_form(form)
  result = form.submit
  find_form(result)
  result
end
with_retry(retries, exception_class, interval = 0.5) { || ... } click to toggle source
# File lib/royal_mail_scraper/tracker/request.rb, line 52
def with_retry(retries, exception_class, interval = 0.5)
  attempt = 0

  begin
    attempt += 1
    yield
  rescue *exception_class => e
    if attempt == retries
      raise e
    else
      sleep interval
      retry
    end
  end
end