class DhlExpress::Tracking

Public Class Methods

new(tracking_number) click to toggle source

Create a new Tracking object.

tracking_number - tracking number of the package to lookup.

Returns an instance of DhlExpress::Tracking.

# File lib/dhl_express/tracking.rb, line 12
def initialize(tracking_number)
  raise ArgumentError unless tracking_number

  @tracking_number = tracking_number
  tracking_url = "http://www.dhl-usa.com/shipmentTracking?AWB=#{@tracking_number}&countryCode=us&languageCode=en"

  @tracking_json = JSON.parse(Typhoeus.get(tracking_url).body)
end

Public Instance Methods

destination() click to toggle source

Destination of the packaage

Returns destination as String.

# File lib/dhl_express/tracking.rb, line 34
def destination
  return nil if tracking_is_empty

  destination = @tracking_json["results"][0]["destination"]["value"].strip
  return destination
end
history() click to toggle source

History of package checkpoints in chronological order

Returns tracking history as Array.

# File lib/dhl_express/tracking.rb, line 54
def history
  return nil if tracking_is_empty

  checkpoints = @tracking_json["results"][0]["checkpoints"]

  history = []

  checkpoints.each do |checkpoint|
    date = dhl_date_string_as_date(checkpoint)
    action = checkpoint["description"].strip
    location = checkpoint["location"].strip

    history << { date: date, action: action, location: location }
  end

  history.sort_by! { |h| h[:date] }

  return history
end
origin() click to toggle source

Origin of the package

Returns origin as String.

# File lib/dhl_express/tracking.rb, line 24
def origin
  return nil if tracking_is_empty

  origin = @tracking_json["results"][0]["origin"]["value"].strip
  return origin
end
status() click to toggle source

Current status of the package in the history

Returns status as String.

# File lib/dhl_express/tracking.rb, line 44
def status
  return nil if tracking_is_empty

  status = @tracking_json["results"][0]["description"].strip
  return status
end

Private Instance Methods

dhl_date_string_as_date(checkpoint) click to toggle source
# File lib/dhl_express/tracking.rb, line 76
def dhl_date_string_as_date(checkpoint)
  date_string = checkpoint["date"]
  month_string_position = date_string.index(",")+2
  date_without_weekday = date_string[month_string_position...date_string.length]
  time = checkpoint["time"]

  date = Chronic.parse("#{date_without_weekday} at #{time}") rescue nil
  return date
end
tracking_is_empty() click to toggle source
# File lib/dhl_express/tracking.rb, line 86
def tracking_is_empty
  if @tracking_json["results"].nil?
    return true
  else
    return false
  end
end