Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Assignment #2 #8

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 19 additions & 6 deletions lib/api.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
24 changes: 21 additions & 3 deletions movie_json.rb
Original file line number Diff line number Diff line change
@@ -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
Expand Down
4 changes: 4 additions & 0 deletions spec/api_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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