Created
July 8, 2013 18:51
-
-
Save eToThePiIPower/5951430 to your computer and use it in GitHub Desktop.
A simple seeds.rb to seed a rails app with data from Yahoo Local. Uses Yahoo's public API so no API key is required.
This file contains 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
#/db/seeds.rb | |
require 'open-uri' # Needed to open web urls | |
Restaurant.delete_all | |
zip = "10006" # Set a search zip | |
returns_per_term = 5 # How many restaurants to return per query | |
owner = Owner.first # Need an owner | |
terms = ["burgers", "italian", "deli", "coffee", "cuban", "japanese", "steakhouse"] # Terms to search for, should all names of categories | |
terms.each do |term| | |
# Query the Yahoo Local API | |
url = "http://local.yahooapis.com/LocalSearchService/V3/localSearch?appid=YahooDemo&query=#{term}&zip=#{zip}&results=#{returns_per_term}&output=json" | |
json = open(url) | |
#Parse the JSON into a hash | |
parsed = ActiveSupport::JSON.decode(json) | |
parsed['ResultSet']['Result'].each do |result| | |
address1 = result['Address'] | |
address1 = "Unknown" if address1.empty? # Some address fields are empty, validations will complain otherwise | |
restaurant = owner.restaurants.create!({ | |
name: result['Title'], | |
description: "Replace Me", | |
address1: address1, | |
city: result['City'], | |
state: result['State'], | |
zip: zip, | |
phone: result['Phone'] | |
# If you store the address as a single string instead of separate address1/address2/city/state/zip fields | |
# Use the following code instead | |
# address: "#{Result['Address']}\nResult['City'], Result['State'] #{zip}" | |
}) | |
restaurant.categories << Category.where({name: term}).first | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment