Redial: AGI and Ruby

This week, Redial had me finally becoming familiar with Ruby. We used AGI (Asterisk Gateway Interface) to pull info from the web and have it do something over the phone. My application takes two zipcodes entered on the keypad and sends them to a web service that calculates the distance between them. That distance is then read back to the caller.

Super quick and dirty, no error handling or input validation. Here’s the extensions.conf – it takes the two zip codes and sends it to Ruby:

1
2
3
4
5
[zip]
exten => s,1,Answer()
same => n,Read(zipA,"beep",5)
same => n,Read(zipB,"beep",5)
same => n,AGI(zip.rb,${zipA},${zipB})

And here’s zip.rb – it takes the zip codes, sends them to this zip code distance API, gets the XML response and tells AGI to read it back to the caller:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#!/usr/bin/ruby

require 'rubygems'
require 'ruby-agi'
require 'net/http'
require 'rexml/document'

agi = AGI.new

zipA = ARGV[0]
zipB = ARGV[1]

url = "http://zipcodedistanceapi.cymi.org/rest/distance.xml/" + zipA + "/" + zipB + "/mile"
response = Net::HTTP.get_response(URI.parse(url)).body
doc = REXML::Document.new(response)
miles = REXML::Functions.number(doc.get_text('response/distance')).floor

agi.say_number(miles)