-
Notifications
You must be signed in to change notification settings - Fork 0
/
movie_finder.rb
66 lines (54 loc) · 1.78 KB
/
movie_finder.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
require 'json'
require 'typhoeus'
require './movie_search_cache.rb'
class MovieFinder
attr_reader :title, :release_year, :imdb_ids, :movies, :api_limit_reached
def initialize(title, release_year = nil)
@title = title.downcase
@release_year = release_year
@imdb_ids = imdb_ids
@movies = find_movies
@api_limit_reached = initial_response["Error"] == "Request limit reached!"
end
def imdb_title_results
"https://www.imdb.com/find?q=#{title}&s=tt"
end
private
def find_movies
return unless imdb_ids
# improve performance by caching requests and making requests in parallel
hydra = Typhoeus::Hydra.new
requests = parallel_requests(hydra)
hydra.run
requests.map do |request|
response = JSON.parse(request.response.body) if request.response.code == 200
response["imdb_page"] = imdb_page(response["imdbID"])
response
end
end
def imdb_ids
body = initial_response
initial_results = body["Search"]
return unless initial_results
initial_results.map { |result| result["imdbID"] }
end
def initial_response
JSON.parse(initial_request.body)
end
# first response returns list of movie objects with imdbID keys
# imdb id only accessible by first doing a generic search
# once relevant ids are available, we can get more complete details by requesting with the id parameter
def initial_request
Typhoeus.get("https://www.omdbapi.com/?apikey=#{ENV["OMDB_API_KEY"]}&s=#{title}&type=movie&y=#{release_year}")
end
def parallel_requests(hydra)
imdb_ids.map do |id|
request = Typhoeus::Request.new("https://www.omdbapi.com/?apikey=#{ENV["OMDB_API_KEY"]}&i=#{id}")
hydra.queue(request)
request
end
end
def imdb_page(id)
"https://www.imdb.com/title/#{id}"
end
end