lib/google_geocode.rb in google-geocode-1.1.0 vs lib/google_geocode.rb in google-geocode-1.2.0

- old
+ new

@@ -1,19 +1,18 @@ -require 'open-uri' -require 'rexml/document' +require 'rc_rest' ## # Library for looking up coordinates with Google's Geocoding API. # # http://www.google.com/apis/maps/documentation/#Geocoding_HTTP_Request -class GoogleGeocode +class GoogleGeocode < RCRest ## # Base error class - class Error < RuntimeError; end + class Error < RCRest::Error; end ## # Raised when you try to locate an invalid address. class AddressError < Error; end @@ -44,11 +43,12 @@ def locate(address) get :q => address end - private + ## + # Extracts a Location from +xml+. def parse_response(xml) l = Location.new l.address = xml.elements['/kml/Response/Placemark/address'].text @@ -57,14 +57,15 @@ l.longitude, l.latitude, = coordinates.split(',').map { |v| v.to_f } return l end - def check_error(obj) - obj = REXML::Document.new obj.read unless REXML::Document === obj + ## + # Extracts and raises an error from +xml+, if any. - status = obj.elements['/kml/Response/Status/code'].text.to_i + def check_error(xml) + status = xml.elements['/kml/Response/Status/code'].text.to_i case status when 200 then # ignore, ok when 500 then raise Error, 'server error' when 601 then @@ -80,34 +81,18 @@ else raise Error, "unknown error #{status}" end end - def get(params) - url = make_url params + ## + # Creates a URL from the Hash +params+. Automatically adds the key and + # sets the output type to 'xml'. - url.open do |xml| - res = REXML::Document.new xml.read - - check_error res - return parse_response(res) - end - rescue OpenURI::HTTPError => e - check_error e.io - raise - end - def make_url(params) params[:key] = @key params[:output] = 'xml' - escaped_params = params.sort_by { |k,v| k.to_s }.map do |k,v| - "#{URI.escape k.to_s}=#{URI.escape v.to_s}" - end - - url = @url.dup - url.query = escaped_params.join '&' - return url + super params end end ##