Class: HTTPConn

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

Overview

Connection allows the creation of an HTTP/HTTPS connection

that allows the issues of HTTP requests.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(url, settings = {}) ⇒ HTTPConn

Returns a new instance of HTTPConn.



10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/http_conn.rb', line 10

def initialize(url, settings = {})
  @started = false
  @http = nil
  @url = url

  self.settings = {
    header: {},
    ssl: false,
    cert: "",
    read_timeout: 60
  }
  self.settings.merge!(settings)
end

Instance Attribute Details

#settingsObject

Returns the value of attribute settings.



7
8
9
# File 'lib/http_conn.rb', line 7

def settings
  @settings
end

#urlObject (readonly)

Returns the value of attribute url.



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

def url
  @url
end

Instance Method Details

#get(options = {}) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/http_conn.rb', line 24

def get(options = {})
  default = {
    end_point: "",
    header: {},
    query_str: {}
  }
  options = default.merge(options)
  url = query_str("#{@url}#{options[:end_point]}", options[:query_str])

  uri = URI(url)
  http = @started ? @http : get_http(uri)
  request = Net::HTTP::Get.new(uri.request_uri,
                               settings[:header].merge(options[:header]))
  http.request(request)
end

#post(options = {}) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/http_conn.rb', line 40

def post(options = {})
  default = {
    end_point: "",
    header: {},
    body: nil
  }
  options = default.merge(options)
  uri = URI("#{@url}#{options[:end_point]}")

  http = @started ? @http : get_http(uri)
  request = Net::HTTP::Post.new(uri.request_uri,
                                settings[:header].merge(options[:header]))
  http.request(request, options[:body])
end

#start(uri = nil) ⇒ Object



55
56
57
58
59
60
61
62
# File 'lib/http_conn.rb', line 55

def start(uri = nil)
  @started = true
  @http = uri.nil? ? get_http(URI(@url)) : get_http(URI(uri))
  @http.start
  yield
  @http.finish # Close connection after usage in 'yield'.
  @started = false
end