Class: Koko::Tracker::Request

Inherits:
Object
  • Object
show all
Includes:
Logging, Utils
Defined in:
lib/koko/tracker/request.rb

Constant Summary

Constants included from Utils

Utils::UTC_OFFSET_WITHOUT_COLON, Utils::UTC_OFFSET_WITH_COLON

Class Attribute Summary collapse

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Logging

included, logger, #logger, logger=

Methods included from Utils

#date_in_iso8601, #datetime_in_iso8601, #formatted_offset, #isoify_dates, #isoify_dates!, #seconds_to_utc_offset, #stringify_keys, #symbolize_keys, #symbolize_keys!, #time_in_iso8601, #uid

Constructor Details

#initialize(options = {}) ⇒ Request

public: Creates a new request object to send analytics batch



19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/koko/tracker/request.rb', line 19

def initialize(options = {})
  options[:host] ||= Defaults::Request.host
  options[:port] ||= Defaults::Request.port
  options[:ssl] ||= Defaults::Request.ssl
  options[:headers] ||= Defaults::Request.headers
  @path = options[:path] || Defaults::Request.path

  http = Net::HTTP.new(options[:host], options[:port])
  http.use_ssl = options[:ssl]
  http.read_timeout = 8
  http.open_timeout = 4

  @http = http
end

Class Attribute Details

.stubObject

Returns the value of attribute stub.



71
72
73
# File 'lib/koko/tracker/request.rb', line 71

def stub
  @stub
end

Instance Attribute Details

#httpObject (readonly)

Returns the value of attribute http.



15
16
17
# File 'lib/koko/tracker/request.rb', line 15

def http
  @http
end

Instance Method Details

#post(auth, body) ⇒ Object

public: Posts the write key and batch of messages to the API.

returns - Response of the status and error if it exists



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
# File 'lib/koko/tracker/request.rb', line 37

def post(auth, body)
  status = nil
  headers = { 'Content-Type' => 'application/json' }

  begin
    payload = JSON.generate body
    request = Net::HTTP::Post.new(@path, headers)
    request['authorization'] = auth

    response = nil

    if self.class.stub
      status = 200
      logger.debug "stubbed request to #{@path}: auth = #{auth}, payload = #{payload}"
    else
      res = @http.request(request, payload)
      status = res.code.to_i
      if status < 500
        response = JSON.parse(res.body)
      else
        response = res.body
      end
    end
  rescue Exception => e
    logger.error e.message
    e.backtrace.each { |line| logger.error line }
    status = -1
    response = "Connection error: #{e}"
  end

  Response.new status, response
end