diff --git a/lib/api.rb b/lib/api.rb index a8d499c..93c9e44 100644 --- a/lib/api.rb +++ b/lib/api.rb @@ -2,20 +2,33 @@ require "json" require "ostruct" require_relative "./movie" + class Api + class MovieNotFoundError < StandardError; end + APIKEY="4t6456xa33z8qhcqyuqgnkjh" def self.search_by_title(title) url = "http://api.rottentomatoes.com/api/public/v1.0/movies.json?apikey=#{APIKEY}&q=#{URI.encode(title)}&page_limit=1" - struct = OpenStruct.new(get_url_as_json(url).fetch("movies").first) - Movie.new(id: struct.id.to_i, - title: struct.title, - year: struct.year, - score: struct.ratings["critics_score"] - ) + + raw_result_json = get_url_as_json(url) + build_movie_from_result(raw_result_json) + end + def self.build_movie_from_result(json) + if json["movies"].count > 0 + struct = OpenStruct.new(json.fetch("movies").first) + Movie.new(id: struct.id.to_i, + title: struct.title, + year: struct.year, + score: struct.ratings["critics_score"] + ) + else + raise MovieNotFoundError + end + end def self.get_url_as_json(url) JSON.parse(open(url).read) diff --git a/movie_json.rb b/movie_json.rb index d8a91d7..598053b 100644 --- a/movie_json.rb +++ b/movie_json.rb @@ -1,11 +1,29 @@ require_relative "lib/movie" require_relative "lib/api" +def get_average(movies) + averages = [] + + movies.each do |m| + averages << m.score + end + + averages.inject{ |sum, el| sum + el }.to_f / averages.size + +end + def find_movie - puts "OH HAI. Search?" + puts "Add a movie you really like" movie_title = gets - movie = Api.search_by_title(movie_title) - puts "Found: #{movie.title}. Score: #{movie.score}" + @movies = [] if @movies.nil? + + begin + @movies << Api.search_by_title(movie_title) + puts "Found: #{@movies.last.title}. Score: #{@movies.last.score}. Avg. Score: #{get_average(@movies)}" + rescue Api::MovieNotFoundError + puts "Movie was not found :( :( " + end + end find_movie diff --git a/spec/api_spec.rb b/spec/api_spec.rb index 9014106..e2d9fbf 100644 --- a/spec/api_spec.rb +++ b/spec/api_spec.rb @@ -24,4 +24,8 @@ it "should return the year" do movie.year.should eq(1994) end + + it "should not blow up" do + expect { Api.search_by_title("NOTHINGFOUNDHERE") }.to_not raise_error + end end