Skip to content

Instantly share code, notes, and snippets.

@dansitu
Created April 14, 2011 12:53
Show Gist options
  • Save dansitu/919409 to your computer and use it in GitHub Desktop.
Save dansitu/919409 to your computer and use it in GitHub Desktop.
Some Ruby sample code
require 'uri'
require 'net/http'
require 'json'
# Here's my Ruby 'FizzBuzz'. I've searched far and wide and
# haven't found one I like better.
def fizzbuzz
1.upto(100) do |number|
message = "#{"Fizz" if number % 3 == 0}#{"Buzz" if number % 5 == 0}"
puts message.empty? ? number : message
end
end
# This thing fetches a list of places from the Twitter API,
# using 'accuracy' as a simple way to specify a range around a point.
# It returns them as JSON for eventual displayed on a Google map.
def get_places_with_accuracy(accuracy, lat, long)
urlstring = 'http://api.twitter.com'
url = URI.parse(urlstring)
#http://dev.twitter.com/doc/get/geo/search
response = Net::HTTP.start(url.host, url.port) { |http|
http.get("/1/geo/search.json?lat=#{lat}&long=#{long}&accuracy=#{accuracy}&granularity=poi&max_results=100")
}
json_response = JSON.parse(response.body)
if json_response.nil? or !json_response['errors'].nil? then
return JSON.generate []
end
places_list = json_response['result']['places']
places_relevant_info = places_list.collect { |place|
{:name => place['name'],
:id => place['id'],
:long => lambda{ |place|#this stuff just gets the center of the bounding box
first = place['bounding_box']['coordinates'][0][0].first
second = place['bounding_box']['coordinates'][0][1].first
return second + ((first - second)/2)
}.call(place),
:lat => lambda{ |place|
first = place['bounding_box']['coordinates'][0][1].last
second = place['bounding_box']['coordinates'][0][2].last
return first + ((second - first)/2)
}.call(place)
}
}
return JSON.generate places_relevant_info
end
def test_get_places_with_accuracy
places = JSON.parse get_places_with_accuracy(100, '37.7821120598956','-122.400612831116')
puts "The search returned #{places.length} places."
places.sort! {|a,b| a["name"].length <=> b["name"].length}
puts "Longest place name is #{places.last["name"]}."
puts "I'll return a random place."
places[rand(places.length + 1)]
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment