Class: MosEisley::HTTPClient

Inherits:
Object
  • Object
show all
Defined in:
lib/http-client/client.rb

Class Method Summary collapse

Class Method Details

.post_form(url:, params: nil, head: nil, &block) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
# File 'lib/http-client/client.rb', line 6

def self.post_form(url:, params: nil, head: nil, &block)
  if EM.reactor_running?
    MosEisley.logger.debug("POSTing form to #{url}")
    MosEisley::HTTPClient.request(url: url, head: head, body: params, &block)
  else
    MosEisley.logger.debug('Starting reactor...')
    EM.run do
      MosEisley.logger.debug("POSTing form to #{url}")
      MosEisley::HTTPClient.request(url: url, head: head, body: params, stop: true, &block)
    end
  end
end

.post_json(url:, params: nil, body: nil, head: {}, &block) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/http-client/client.rb', line 19

def self.post_json(url:, params: nil, body: nil, head: {}, &block)
  head['Content-Type'] = 'application/json; charset=utf-8'
  body = S3PO.json_with_object(params) if params
  if EM.reactor_running?
    MosEisley.logger.debug("POSTing JSON to: #{url}")
    MosEisley::HTTPClient.request(url: url, head: head, body: body, &block)
  else
    MosEisley.logger.debug('Starting reactor...')
    EM.run do
      MosEisley.logger.debug("POSTing JSON to #{url}")
      MosEisley::HTTPClient.request(url: url, head: head, body: body, stop: true, &block)
    end
  end
end

.request(url:, head: nil, body:, stop: false, &block) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/http-client/client.rb', line 34

def self.request(url:, head: nil, body:, stop: false, &block)
  http = EM::HttpRequest.new(url).post(body: body, head: head)
  http.errback do
    MosEisley.logger.error('HTTP error')
    if stop
      EM.stop
      MosEisley.logger.debug('Stopped reactor.')
    end
  end
  http.callback do
    block.call(http) if block_given?
    if stop
      EM.stop
      MosEisley.logger.debug('Stopped reactor.')
    end
  end
end