Class: Swapir

Inherits:
Object
  • Object
show all
Includes:
ResourceApi, ResourceListApi, ResourceSearchApi
Defined in:
lib/swapir.rb

Class Method Summary collapse

Methods included from ResourceSearchApi

included

Methods included from ResourceApi

included

Methods included from ResourceListApi

included

Class Method Details

.api_available?Boolean

Returns:

  • (Boolean)


26
27
28
29
30
31
32
33
34
# File 'lib/swapir.rb', line 26

def self.api_available?
  # allow an exception to be raised if the request fails
  # handle the raised exception
  begin
    RestClient.get(api_base_url).code == 200
  rescue Errno::ECONNREFUSED => e
    false
  end
end

.api_base_urlObject



21
22
23
24
# File 'lib/swapir.rb', line 21

def self.api_base_url
  # base Star Wars public api url
  "http://swapi.co/api/"
end

.decode(response) ⇒ Object



47
48
49
50
51
# File 'lib/swapir.rb', line 47

def self.decode(response)
  # convert the Star Wars Api response body
  # return the data in a Ruby Hash
  JSON.parse(response.body)
end

.decode_results(response) ⇒ Object



53
54
55
56
57
# File 'lib/swapir.rb', line 53

def self.decode_results(response)
  # convert the Star Wars Api response body collection
  # return the data collection in a Ruby Hash
  JSON.parse(response.body)["results"]
end

.request(resource) ⇒ Object



36
37
38
39
40
41
42
43
44
45
# File 'lib/swapir.rb', line 36

def self.request(resource)
  return "" unless self.api_available?
  # call the Star Wars Api endpoint returns the api response
  # and does not raise an exception when it fails
  begin
    RestClient.get(api_base_url + resource)
  rescue RestClient::ExceptionWithResponse => e
    e.response
  end
end