Module: Forwardlytics

Defined in:
lib/forwardlytics.rb,
lib/forwardlytics/track.rb,
lib/forwardlytics/version.rb,
lib/forwardlytics/identify.rb

Defined Under Namespace

Classes: NetException

Constant Summary collapse

VERSION =
"1.0.0"

Class Method Summary collapse

Class Method Details

.exception_handler(ex) ⇒ Object



44
45
46
47
48
# File 'lib/forwardlytics.rb', line 44

def self.exception_handler(ex)
  if @exception_handler
    @exception_handler.call(ex)
  end
end

.exception_handler=(handler) ⇒ Object



40
41
42
# File 'lib/forwardlytics.rb', line 40

def self.exception_handler=(handler)
  @exception_handler = handler
end

.identify(user_id:, traits: {}) ⇒ Object



2
3
4
5
6
7
8
9
10
# File 'lib/forwardlytics/identify.rb', line 2

def self.identify(user_id:, traits: {})
  params = {
    userID: user_id,
    userTraits: traits,
    timestamp: Time.now().to_i
  }

  t = Thread.new { post('/identify', params) }
end

.post(uri, params) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/forwardlytics.rb', line 13

def self.post(uri, params)
  begin
    # Forces the user_id to be a string, which is the expected format by Forwardlytics (the server part)
    params[:userID] = params[:userID].to_s unless params[:userID].nil?

    full_url = URI("#{FORWARDLYTICS_URL}#{uri}")
    http = Net::HTTP.new(full_url.host, full_url.port)
    if full_url.port == 443
      http.use_ssl = true
      http.verify_mode = OpenSSL::SSL::VERIFY_PEER
    end
    req = Net::HTTP::Post.new(full_url, initheader = {'Content-Type' =>'application/json'})
    req['Forwardlytics-Api-Key'] = FORWARDLYTICS_API_KEY
    req.body = params.to_json
    res = http.request(req)

    case res
    when Net::HTTPSuccess, Net::HTTPRedirection
      # OK
    else
      raise NetException, "Potential problem posting to Forwardlytics (#{full_url}) - #{res.inspect} - #{res.code} - #{res.body}"
    end
  rescue Exception => ex
    exception_handler(ex)
  end
end

.track(event:, user_id:, properties: {}) ⇒ Object



2
3
4
5
6
7
8
9
10
11
# File 'lib/forwardlytics/track.rb', line 2

def self.track(event:, user_id:, properties: {})
  params = {
    name: event,
    userID: user_id,
    properties: properties,
    timestamp: Time.now().to_i
  }

  t = Thread.new { post('/track', params) }
end