Created
June 27, 2012 22:14
-
-
Save chebyte/3007202 to your computer and use it in GitHub Desktop.
yahoo yql with ruby and oatuh
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
require 'oauth' | |
require 'json' | |
module Yahoo | |
CONSUMER_KEY = "...." | |
CONSUMER_SECRET = "...." | |
class GeoLoc | |
def initialize(consumer_key = CONSUMER_KEY, consumer_secret = CONSUMER_SECRET) | |
@consumer_key = consumer_key | |
@consumer_secret = consumer_secret | |
access_token | |
end | |
def access_token | |
@access_token ||= OAuth::AccessToken.new(OAuth::Consumer.new(@consumer_key, @consumer_secret, :site => "http://query.yahooapis.com")) | |
end | |
def escape string | |
OAuth::Helper.escape(string) | |
end | |
def make_query_url url | |
"/v1/yql?q=#{OAuth::Helper.escape(url)}&format=json" | |
end | |
def query_api url | |
JSON.parse access_token.request(:get, make_query_url(url)).body | |
end | |
def find_by_address string | |
address_url = "SELECT centroid from geo.places WHERE text='#{string}'" | |
Location.new query_api(address_url) | |
end | |
def find sql | |
query_api(sql) | |
end | |
end | |
class Location | |
def initialize(response) | |
@response = response | |
end | |
def latitude | |
if results = @response["query"]["results"] | |
results["place"].is_a?(Array) ? results["place"].last["centroid"]["latitude"] : results["place"]["centroid"]["latitude"] | |
else | |
nil | |
end | |
end | |
def longitude | |
if results = @response["query"]["results"] | |
results["place"].is_a?(Array) ? results["place"].last["centroid"]["longitude"] : results["place"]["centroid"]["longitude"] | |
else | |
nil | |
end | |
end | |
def coords | |
(latitude && longitude) ? "#{latitude}, #{longitude}" : nil | |
end | |
end | |
end | |
client = Yahoo::GeoLoc.new.find_by_address("9 de julio 900, tucuman, san miguel de tucuman").coords #-26.826031, -65.232841 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment