Class: Starwars::Request

Inherits:
Object
  • Object
show all
Defined in:
lib/starwars/request.rb

Overview

Wrap request attrs

Constant Summary collapse

BASE_URL =
'http://swapi.co/api'
FORMAT =
'application/json'

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(attrs) ⇒ Starwars::Request

Initializer

Examples:

data = Request.new(resource: Person.new(id: 1), uri: "/something")

Parameters:

  • attrs (Hash)

    request attributes

Options Hash (attrs):

  • :resource (Starwars::)
  • :method (Symbol)
  • :uri (String)
  • :params (Hash)
  • :as (String)


45
46
47
48
49
50
51
# File 'lib/starwars/request.rb', line 45

def initialize(attrs)
  self.resource = attrs.fetch(:resource)
  self.method = attrs.fetch(:method) { :get }
  self.uri = attrs.fetch(:uri)
  self.as = attrs.fetch(:as) { FORMAT }
  self.params = attrs.fetch(:params) { {} }
end

Instance Attribute Details

#asString

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

The format of the HTTP request

Returns:

  • (String)


12
13
14
# File 'lib/starwars/request.rb', line 12

def as
  @as
end

#methodSymbol

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

The http method for the request

Returns:

  • (Symbol)


17
18
19
# File 'lib/starwars/request.rb', line 17

def method
  @method
end

#paramsHash

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Extra params we want to send with the http request

Returns:

  • (Hash)


32
33
34
# File 'lib/starwars/request.rb', line 32

def params
  @params
end

#resourcePerson, ...

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

The resouce object that we going to call to fetch the data



22
23
24
# File 'lib/starwars/request.rb', line 22

def resource
  @resource
end

#uriString

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

The remote url for the resource that we want to fetch

Returns:

  • (String)


27
28
29
# File 'lib/starwars/request.rb', line 27

def uri
  @uri
end

Instance Method Details

#perform_requestPerson, ...

Delegate to the Roar client to fetch data from api

Examples:

request.perform_request

Returns:

Raises:



60
61
62
63
64
65
# File 'lib/starwars/request.rb', line 60

def perform_request
  resource.send(method, uri: uri, as: as)

  rescue Roar::Transport::Error => e
    raise_http_errors(e.response.code.to_i, e.response.msg)
end