Class: SimpleSegment::Request

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

Constant Summary collapse

BASE_URL =
'https://api.segment.io'
DEFAULT_HEADERS =
{
  'Content-Type' => 'application/json',
  'accept' => 'application/json'
}.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(client) ⇒ Request



13
14
15
16
17
18
19
# File 'lib/simple_segment/request.rb', line 13

def initialize(client)
  @write_key = client.config.write_key
  @error_handler = client.config.on_error
  @stub = client.config.stub
  @logger = client.config.logger
  @http_options = client.config.http_options
end

Instance Attribute Details

#error_handlerObject (readonly)

Returns the value of attribute error_handler.



11
12
13
# File 'lib/simple_segment/request.rb', line 11

def error_handler
  @error_handler
end

#http_optionsObject (readonly)

Returns the value of attribute http_options.



11
12
13
# File 'lib/simple_segment/request.rb', line 11

def http_options
  @http_options
end

#loggerObject (readonly)

Returns the value of attribute logger.



11
12
13
# File 'lib/simple_segment/request.rb', line 11

def logger
  @logger
end

#stubObject (readonly)

Returns the value of attribute stub.



11
12
13
# File 'lib/simple_segment/request.rb', line 11

def stub
  @stub
end

#write_keyObject (readonly)

Returns the value of attribute write_key.



11
12
13
# File 'lib/simple_segment/request.rb', line 11

def write_key
  @write_key
end

Instance Method Details

#post(path, payload, headers: DEFAULT_HEADERS) ⇒ Object

rubocop:disable Metrics/AbcSize, Metrics/MethodLength



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/simple_segment/request.rb', line 21

def post(path, payload, headers: DEFAULT_HEADERS) # rubocop:disable Metrics/AbcSize, Metrics/MethodLength
  response = nil
  status_code = nil
  response_body = nil

  uri = URI(BASE_URL)
  payload = JSON.generate(payload)
  if stub
    logger.debug "stubbed request to \
    #{path}: write key = #{write_key}, \
    payload = #{payload}"

    { status: 200, error: nil }
  else
    Net::HTTP.start(uri.host, uri.port, :ENV, http_options) do |http|
      request = Net::HTTP::Post.new(path, headers)
      request.basic_auth write_key, nil
      http.request(request, payload).tap do |res|
        status_code = res.code
        response_body = res.body
        response = res
        response.value
      end
    end
  end
rescue StandardError => e
  error_handler.call(status_code, response_body, e, response)
end