-
Notifications
You must be signed in to change notification settings - Fork 0
/
bookapp.rb
52 lines (40 loc) · 1.67 KB
/
bookapp.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
#!/usr/bin/env ruby
#Author: Mansoor Khan ([email protected])
#Date: July 21, 2016
#License: The MIT License (MIT)
#Search for books via GoogleBooksAPI with the specified query
require "bookapp/version"
require 'net/https'
require 'json'
require 'uri'
require 'cgi'
#To temporary disable SSL connect error, uncomment the following line
OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE
module Bookapp
class BookSearch
def search(query ="")
url = 'https://www.googleapis.com/books/v1/volumes?q='+CGI::escape(query)
uri = URI(url)
response = Net::HTTP.get(uri)
response = JSON.parse(response, symbolize_names: true)
puts "Books for '#{query}':"
response[:items].each_with_index do |book, index|
print index+1, ". Title: ", book[:volumeInfo][:title], "\n",
" Author(s): ", book[:volumeInfo][:authors].map{|author| author}.join(","), "\n"
print " Published: ", book[:volumeInfo][:publishedDate], "\n" if book[:volumeInfo][:publishedDate]
print " Average Rating: ", book[:volumeInfo][:averageRating], " (",book[:volumeInfo][:ratingsCount], ")", "\n" if book[:volumeInfo][:averageRating]
print " Price: ", book[:saleInfo][:retailPrice][:currencyCode]," ", book[:saleInfo][:retailPrice][:amount], "\n" if book[:saleInfo][:retailPrice]
puts "\n\n"
end
end
end
# Get the arguments from the command line
# Call search method with the arguments to search for books
# with the specified query
if ARGV.size == 0 || ARGV[0].strip == ""
puts "Please provide search query as an argument"
else
query = ARGV[0].strip
BookSearch.new.search(query)
end
end