diff --git a/lib/geocoder/lookups/base.rb b/lib/geocoder/lookups/base.rb index c8d843409a6efd0447ef3728f780a4c3931d958e..64b72b9b5a0a4df930eacf9df1789a01ea7559a9 100644 --- a/lib/geocoder/lookups/base.rb +++ b/lib/geocoder/lookups/base.rb @@ -1,5 +1,11 @@ require 'net/http' -require 'json' +unless defined? ActiveSupport::JSON + begin + require 'json' + rescue LoadError + raise LoadError, "Please install the json gem to parse geocoder results." + end +end module Geocoder module Lookup @@ -49,14 +55,27 @@ module Geocoder # def fetch_data(query, reverse = false) begin - JSON.parse(fetch_raw_data(query, reverse)) + parse_raw_data fetch_raw_data(query, reverse) rescue SocketError warn "Geocoding API connection cannot be established." rescue TimeoutError warn "Geocoding API not responding fast enough " + "(see Geocoder::Configuration.timeout to set limit)." - rescue JSON::ParseError - warn "Geocoding API's response was not valid JSON." + end + end + + ## + # Parses a raw search result (returns hash or array). + # + def parse_raw_data(raw_data) + if defined?(JSON) + begin + JSON.parse(raw_data) + rescue JSON::ParseError + warn "Geocoding API's response was not valid JSON." + end + elsif defined?(ActiveSupport::JSON) + ActiveSupport::JSON.decode(raw_data) end end