-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.rb
82 lines (73 loc) · 2.5 KB
/
utils.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# Copyright 2013 Kevin Shekleton
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'json'
require 'net/http'
require 'uri'
# Various utilities around using the Comic Vine API.
class Utils
@@api_key = File.open('API-KEY', 'r:utf-8').read
if @@api_key == nil || 'REPLACE_WITH_YOUR_OWN_COMIC_VINE_API_KEY' == @@api_key
raise <<-eos
No API key is defined.
You must define your Comic Vine API key in the file API-KEY.
If you don't have an API key, head on over to http://www.comicvine.com/api/ and register as a developer.
eos
end
def self.api_key
@@api_key
end
# Executes a GET for the given Comic Vine URL.
#
# url - The URL to execute (cannot be nil).
#
# See http://www.comicvine.com/api/documentation#toc-0-0
#
# Returns the non-nil JSON response if the GET request was successfull; nil otherwise.
def self.execute_get(url)
response = Net::HTTP.get(URI.parse(url))
json = JSON.parse(response)
if json['status_code'] != 1
raise "Failure encountered while calling #{url}\nstatus_code: #{json['status_code']}\nerror: #{json['error']}"
end
json
end
end
class String
# Signs the given URL with the configured API key.
# Examples:
# 'http://www.comicvine.com/api/search/'.sign
#
# Returns the signed URL String.
def sign
"#{self}?api_key=#{Utils.api_key}"
end
# Adds the format filter to the URL denoting that the JSON Content-Type is desired.
# Examples:
# 'http://www.comicvine.com/api/search/'.sign.accept_json
#
# Returns the modified URL String.
def accept_json
"#{self}&format=json"
end
# Adds the field_list filter to the URL with the given fields.
# Examples:
# 'http://www.comicvine.com/api/search/'.sign.return_fields :name
# 'http://www.comicvine.com/api/search/'.sign.return_fields :name, :api_detail_url
#
# fields - A vararg list of fields that should be returned (cannot be nil)
#
# Returns the modified URL String.
def return_fields(*fields)
"#{self}&field_list=#{fields.join(',')}"
end
end