Skip to content

Instantly share code, notes, and snippets.

@mmichael0413
Created October 17, 2014 03:59
Show Gist options
  • Save mmichael0413/56406a11338e349dae8a to your computer and use it in GitHub Desktop.
Save mmichael0413/56406a11338e349dae8a to your computer and use it in GitHub Desktop.
Use TMDB API to create local movie objects
# Code for creating a list of 400 movie ids (most popular)
# And then creating a local movie object (along with genres and movie_genres)
api_ids = []
20.times do |i|
resp = HTTParty.get("http://api.themoviedb.org/3/movie/popular?api_key=#{ENV['TMDB_API_KEY']}&page=#{i+1}")
data = JSON.parse(resp.body)
data['results'].each do |movie|
api_ids << movie['id']
end
end
api_ids.each do |id|
resp = HTTParty.get("http://api.themoviedb.org/3/movie/#{id}?api_key=#{ENV['TMDB_API_KEY']}")
data = JSON.parse(resp.body)
mov = Movie.new
mov.backdrop_url = data['backdrop_path']
mov.imdb_id = data['imdb_id']
mov.overview = data['overview']
mov.poster_url = data['poster_path']
mov.release_date = data['release_date']
mov.runtime = data['runtime']
mov.title = data['title']
mov.api_data = data
if mov.save
puts "Success! #{mov.id}) #{mov.title}"
if data.has_key?('genres') && data['genres'].any?
data['genres'].each do |g|
genre = Genre.find_or_create_by(name: g['name'])
genre.save if genre.new_record?
mov.movie_genres.create(genre_id: genre.id)
end
end
else
puts "Error!"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment