-
-
Save n0m4dz/5f0d3ba60b7bfe052686b1448cb22d1f to your computer and use it in GitHub Desktop.
Use TMDB API to create local movie objects
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
| # 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