Class: GcalMapper::RestRequest

Inherits:
Object
  • Object
show all
Defined in:
lib/gcal_mapper/rest_request.rb

Overview

Make a REST get or post request

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(url, options = {}) ⇒ RestRequest

Initialize a new request

Parameters:

  • url (String)

    the complete url of where to send the request



17
18
19
20
# File 'lib/gcal_mapper/rest_request.rb', line 17

def initialize (url, options = {})
  @url = url
  @options = options
end

Instance Attribute Details

#optionsObject

Options for the REST request



11
12
13
# File 'lib/gcal_mapper/rest_request.rb', line 11

def options
  @options
end

#urlObject

Complete url for the request



10
11
12
# File 'lib/gcal_mapper/rest_request.rb', line 10

def url
  @url
end

Instance Method Details

#executeHash

Execute REST request

Returns:

  • (Hash)

    a Json parsed hash that contains the body of the response.



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
# File 'lib/gcal_mapper/rest_request.rb', line 32

def execute
  options = {
    :parameters => {}, :debug => false,
    :http_timeout => 60, :method => :get,
    :headers => {}, :redirect_count => 0,
    :max_redirects => 10
  }.merge(@options)
  url = URI(@url)

  if proxy
    http = Net::HTTP::Proxy(proxy.host, proxy.port).new(url.host, url.port)
  else
    http = Net::HTTP.new(url.host, url.port)
  end

  if url.scheme == 'https'
    http.use_ssl = true
  end

  http.open_timeout = http.read_timeout = options[:http_timeout]
  http.set_debug_output $stderr if options[:debug]

  request = case options[:method]
  when :post
    request = Net::HTTP::Post.new(url.request_uri)
    request.set_form_data(options[:parameters])
    request
  else
      request = Net::HTTP::Get.new(url.request_uri)
  end

  options[:headers].each { |key, value| request[key] = value }
  response = http.request(request)
  if !(200..300).include?(response.code.to_i)
    raise GcalMapper::ResponseStatusError
  end

  JSON.parse(response.body)
end

#proxyObject

Set a proxy if the connection needs it



24
25
26
27
# File 'lib/gcal_mapper/rest_request.rb', line 24

def proxy
  http_proxy = ENV["http_proxy"]
  URI.parse(http_proxy) rescue nil
end