Created
April 23, 2010 01:33
-
-
Save paulhart/376057 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class TwilioPricing | |
attr_reader :pricelist | |
def initialize | |
self.refresh_pricelist | |
end | |
def pricing_for(number, duration = 1) | |
internal_number = number.to_s.scan(/\d/).join('') # cast and filter... | |
if number.length == 10 | |
# I'm going to prefix this with a '1' because it's *probably* North American. | |
internal_number = '1' + internal_number | |
end | |
key = nil | |
internal_number.length.times {|time| | |
hit = @pricelist[internal_number[0..time]] | |
key = hit if hit | |
} | |
if key | |
key[:duration] = duration | |
key[:total_rate] = (key[:rate].to_f * duration.to_i).to_s | |
end | |
key | |
end | |
def refresh_pricelist | |
pricelist = {} | |
rates = open('http://www.twilio.com/resources/rates/international-rates.csv') | |
rates.lines.each {|line| | |
sections = line.split(',') | |
prefixes = sections[2].split(' ') | |
prefixes.each{|prefix| | |
pricelist[prefix] = { | |
:country => sections[0], | |
:rate => sections[1] | |
} | |
} | |
} | |
rates.close! | |
@pricelist = pricelist | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The hash that pricing_for returns has the same key/value pairs as you'll find from the app at http://twilio-rates.appspot.com/
The only difference is that you don't have a 'status' key - if things go wrong or your number isn't found, you'll get nil back.