Class: Plangrade::HttpAdapter

Inherits:
Object
  • Object
show all
Defined in:
lib/plangrade/http_adapter.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(site_url, opts = {}) ⇒ HttpAdapter

Returns a new instance of HttpAdapter.



14
15
16
17
18
19
20
# File 'lib/plangrade/http_adapter.rb', line 14

def initialize(site_url, opts={})
  unless site_url =~ /^https?/
    raise ArgumentError, "site_url must include either http or https scheme"
  end
  @site_url = site_url
  @connection_options = opts
end

Instance Attribute Details

#connection_optionsObject

Returns the value of attribute connection_options.



12
13
14
# File 'lib/plangrade/http_adapter.rb', line 12

def connection_options
  @connection_options
end

#site_urlObject

Returns the value of attribute site_url.



12
13
14
# File 'lib/plangrade/http_adapter.rb', line 12

def site_url
  @site_url
end

Class Method Details

.log=(output) ⇒ Object



8
9
10
# File 'lib/plangrade/http_adapter.rb', line 8

def self.log=(output)
  RestClient.log = output
end

Instance Method Details

#absolute_url(path = '') ⇒ Object



38
39
40
# File 'lib/plangrade/http_adapter.rb', line 38

def absolute_url(path='')
  "#{@site_url}#{path}"
end

#hostObject



30
31
32
# File 'lib/plangrade/http_adapter.rb', line 30

def host
  @host ||= parsed_url.host
end

#schemeObject



34
35
36
# File 'lib/plangrade/http_adapter.rb', line 34

def scheme
  @scheme ||= parsed_url.scheme
end

#send_request(method, path, opts = {}) ⇒ Object



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
# File 'lib/plangrade/http_adapter.rb', line 47

def send_request(method, path, opts={})
  begin
    params  = opts.fetch(:params, {})

    req_opts = self.connection_options.merge({
      :method  => method,
      :headers => opts.fetch(:headers, {})
    })

    case method
    when :get, :delete
      query = Addressable::URI.form_encode(params)
      normalized_path = query.empty? ? path : [path, query].join("?")
      req_opts[:url]  = absolute_url(normalized_path)
    when :post, :put
      req_opts[:payload] = params
      req_opts[:url]     = absolute_url(path)
    else
      raise "Unsupported HTTP method, #{method}"
    end

    resp = RestClient::Request.execute(req_opts)
  
    result = Plangrade::ApiResponse.new(resp.headers, resp.body, resp.code)
  rescue => e
    if e.is_a?(RestClient::ExceptionWithResponse)
      e.response
    else
      raise e
    end
  end
end