Class: HkpostApi::Quote

Inherits:
Object
  • Object
show all
Defined in:
lib/hkpost_api.rb

Overview

Your code goes hereā€¦

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(endpoint = nil) ⇒ Quote

Returns a new instance of Quote.



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

def initialize(endpoint=nil)
  @endpoint=endpoint
  @endpoint||="http://app1.hongkongpost.hk/"
  @endpoint_uri=URI(@endpoint)
end

Class Method Details

.default_instanceObject



58
59
60
# File 'lib/hkpost_api.rb', line 58

def self.default_instance
  @default_instance=Quote.new()
end

Instance Method Details

#form_htmlObject



14
15
16
# File 'lib/hkpost_api.rb', line 14

def form_html
  @form_html||=Nokogiri::HTML(Net::HTTP.get(@endpoint_uri.host, "/calc/eng/overseas/step1.php"))
end

#get_country_listObject



52
53
54
55
# File 'lib/hkpost_api.rb', line 52

def get_country_list
  @country_list||=form_html.css('form[name="overseas_mail"] select[name="destination"] option').inject({}) {|result, n| result[n.text]=n['value'] unless n['value']=='0'; result}
  return @country_list
end

#get_quote(mail_type, weight_in_gram, country_name) ⇒ Object

Raises:

  • (ArgumentError)


22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/hkpost_api.rb', line 22

def get_quote(mail_type, weight_in_gram, country_name)
  country_code=get_country_list[country_name]
  raise ArgumentError.new("Invalid country name #{country_name}") if country_code.nil?
  res=Net::HTTP.post_form(URI("#{@endpoint}/calc/eng/overseas/step2.php"), 'destination'=>country_code, 'mail'=>mail_type, 'weight'=>weight_in_gram)
  res_html=Nokogiri::HTML(res.body)

  rates={}
  rates[:normal]=parse_rate_table(res_html, "Form of Delivery (Normal)")

  rates[:speedpost]=parse_rate_table(res_html, "Form of Delivery (Speedpost)")



  return rates
end

#get_shipment_typesObject



18
19
20
# File 'lib/hkpost_api.rb', line 18

def get_shipment_types
  return form_html.css('form[name="overseas_mail"] input[name="mail"]').collect {|n| n['value'] }
end

#parse_rate_table(res_html, title) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/hkpost_api.rb', line 38

def parse_rate_table(res_html, title)
  els=res_html.search "[text()*='#{title}']"
  table=els.first.ancestors('table').first
  rows=table.css('tr')
  result = {}
  rows[1..rows.length-1].each do |row|
    cells=row.css('td')
    result[cells[1].text.strip]=cells.last.text.strip
  end

  return result

end