Created
March 14, 2012 21:13
-
-
Save libryder/2039545 to your computer and use it in GitHub Desktop.
Example using SimpleXml to parse API query to LocalCallingGuide.com
This file contains hidden or 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
| # lib/local_calling_guide.rb | |
| # This file should be autoloaded when Rails starts | |
| require 'rest_client' | |
| require 'xmlsimple' | |
| class LocalCallingGuide | |
| def initialize | |
| @url = "http://www.localcallingguide.com/xmllocalprefix.php" | |
| end | |
| # This method accepts the first 6 digits of a phone number as two parameters. | |
| # It will return an array of 6 digit strings which correspond to all local | |
| # phone numbers to the number passed in. | |
| # | |
| # For example, given a US number 250.423.2742, npa=250; nxx=423 | |
| def get_numbers(npa, nxx) | |
| # Simple call to the API will yield an XML document, which can be viewed | |
| # here: http://www.localcallingguide.com/xmllocalprefix.php?npa=250&nxx=423 | |
| api_result = RestClient.get @url, { 'params' => { 'npa' => npa, 'nxx' => nxx, 'dir' => 2 } } | |
| # Extract the lca-data node and its containing array and iterate through all | |
| # prefix children extracting the npa and nxx for each | |
| xml_doc = XmlSimple.xml_in(api_result)['lca-data'][0] | |
| local = [] | |
| xml_doc['prefix'].each { |obj| | |
| local.push obj['npa'][0] + obj['nxx'][0] | |
| } | |
| local | |
| end | |
| end |
This file contains hidden or 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
| # Assuming you have been passed a parameter :number | |
| number = params[:number] | |
| # Use your class | |
| lcg = LocalCallingGuide.new.get_numbers(number[0..2], number[3..5]).to_json | |
| # Yields: | |
| # ["250278","250423","250430","250531","250946","778519","250529","250887"] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment