Class: Stalkr::UPS

Inherits:
Base
  • Object
show all
Defined in:
lib/stalkr/ups.rb

Instance Method Summary collapse

Methods inherited from Base

#cleanup_html, extract_id, #fetchurl, is_valid?, #strip_tags

Instance Method Details

#track(id) ⇒ Object



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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/stalkr/ups.rb', line 23

def track(id)

    url = "http://wwwapps.ups.com/WebTracking/processInputRequest?TypeOfInquiryNumber=T&loc=en_US&InquiryNumber1=%CODE%"

    url.gsub!(/%CODE%/, id)
    html = fetchurl(url)

    begin

        detail_scraper = Scraper.define do

            array :keys
            array :vals
            array :lists

            process "#trkNum", :trackingNumber => :text
            process "#tt_spStatus", :status => :text
            process "#fontControl dt", :keys => :text
            process "#fontControl dd", :vals => :text
            process "#fontControl ul.clearfix li", :lists => :text

            result :keys, :vals, :trackingNumber, :status, :lists

        end

        details = detail_scraper.scrape(html)

        if not details.trackingNumber then
            raise "UPS scraper failed"
        end

        ret = Result.new(:UPS)

        ret.status = case details.status.strip.downcase
            when "in transit"
                IN_TRANSIT
            when "delivered"
                DELIVERED
            else
                UNKNOWN
        end

        hash = {}
        details.keys.each_with_index do |k,i|
            hash[k] = details.vals[i]
        end

        if ret.status == DELIVERED then
            delivered_at = cleanup_html( hash["Delivered On:"] )
            ret.delivered_at = DateTime.strptime( delivered_at, "%A, %m/%d/%Y at %I:%M %p" ).to_time
        end

        cleanup_html( details.lists[3] ) =~ /Updated: (.*?)$/
        ret.updated_at = DateTime.strptime( $1, "%m/%d/%Y %I:%M %p" ).to_time

        return ret

    rescue Exception => ex
        raise Stalkr::Error.new(ex, html)

    end

end