Tuesday, November 10, 2009

Country codes for UPS

I'm not a big fan of the UPS site, so I try not to go there unless I have to - so I may be re-inventing the wheel here. I was wanting to do international shipping. While doing that, I found that UPS was kind enough to give a list of 2 Digit country codes with the full names inside their PDF. When you copy and paste, you get something like this:

Afghanistan AF
Åland Islands AX
Albania AL
Algeria DZ
American Samoa AS
Andorra AD
Angola AO
Anguilla AI
Antarctica AQ
Antigua and Barbuda AG
Argentina AR

....

This isn't the most helpful format - not really easy to parse with a bash script. I decided to continue my ruby education and create a short little Ruby script to turn this data into very basic database data. My needs were simple, so I created:

create table country (
 code char(2) not null primary key,
 country varchar(255) not null,
 enabled tinyint(1) default 0
);

I created a flat file with the data from the PDF - similar to above, but a full listing in a file and then wrote this ruby script:


#!/usr/bin/env ruby
  
# the file we want to create
writer = File.open("build-countries.sql", "w+")

# read in all the ups data and write it out in a format we want.
File.open("ups-country-codes.txt", "r") do |reader|
  while (!reader.eof)
   
    # read in a line
    line = reader.gets().chomp()

   
    # split into the 2 parts
    first = line.slice(0,line.length-3)
    second = line.slice(line.length-2,line.length )

    # ruby's string power makes formatting the output a snap
    out = "insert into country (country,code,enabled) values('#{first}','#{second}',0);"
    writer.puts(out);
  end
end

writer.close
#######################################

The result creates some nice SQL for me:

insert into country (country,code,enabled) values('Afghanistan','AF',0);
insert into country (country,code,enabled) values('Åland Islands','AX',0);
insert into country (country,code,enabled) values('Albania','AL',0);
insert into country (country,code,enabled) values('Algeria','DZ',0);
insert into country (country,code,enabled) values('American Samoa','AS',0);
insert into country (country,code,enabled) values('Andorra','AD',0);
insert into country (country,code,enabled) values('Angola','AO',0);
insert into country (country,code,enabled) values('Anguilla','AI',0);
insert into country (country,code,enabled) values('Antarctica','AQ',0);
insert into country (country,code,enabled) values('Antigua and Barbuda','AG',0);
insert into country (country,code,enabled) values('Argentina','AR',0);
......

No comments: