Class: AnalyticsRuby::Request

Inherits:
Object
  • Object
show all
Defined in:
lib/analytics-ruby/request.rb

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Request

public: Creates a new request object to send analytics batch



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/analytics-ruby/request.rb', line 14

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
  @retries = options[:retries] || Defaults::Request::RETRIES
  @backoff = options[:backoff] || Defaults::Request::BACKOFF

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

  @http = http
end

Instance Method Details

#post(secret, batch) ⇒ Object

public: Posts the secret and batch of messages to the API.

returns - Response of the status and error if it exists



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
# File 'lib/analytics-ruby/request.rb', line 34

def post(secret, batch)

  status, error = nil, nil
  remaining_retries = @retries
  backoff = @backoff
  headers = { 'Content-Type' => 'application/json', 'accept' => 'application/json' }
  begin
    payload = JSON.generate :secret => secret, :batch => batch
    res = @http.request(Net::HTTP::Post.new(@path, headers), payload)
    status = res.code.to_i
    body = JSON.parse(res.body)
    error = body["error"]

  rescue Exception => err
    puts "err: #{err}"
    status = -1
    error = "Connection error: #{err}"
    puts "retries: #{remaining_retries}"
    unless (remaining_retries -=1).zero?
      sleep(backoff)
      retry
    end
  end

  Response.new status, error
end