Module: Clamp::Analytics

Defined in:
lib/clamp_analytics.rb,
lib/clamp_analytics/money.rb,
lib/clamp_analytics/errors.rb,
lib/clamp_analytics/version.rb

Defined Under Namespace

Classes: Error, HTTPError, Money, NotInitializedError

Constant Summary collapse

DEFAULT_ENDPOINT =
"https://api.clamp.sh"
VERSION =
"0.1.0"

Class Method Summary collapse

Class Method Details

.init(project_id:, api_key:, endpoint: nil) ⇒ Object

Initialize the SDK. Call once at application boot (Rails initializer, Sinatra setup block, etc.).



33
34
35
36
37
38
39
40
41
# File 'lib/clamp_analytics.rb', line 33

def init(project_id:, api_key:, endpoint: nil)
  @mutex.synchronize do
    @config = {
      project_id: project_id,
      api_key: api_key,
      endpoint: endpoint || DEFAULT_ENDPOINT
    }
  end
end

.reset!Object

Reset all SDK state. Intended for tests.



82
83
84
85
86
87
# File 'lib/clamp_analytics.rb', line 82

def reset!
  @mutex.synchronize do
    @config = nil
    @transport = nil
  end
end

.track(name, properties: {}, anonymous_id: nil, timestamp: nil) ⇒ true

Track a server-side event.

Parameters:

  • name (String)

    event name

  • properties (Hash) (defaults to: {})

    optional, values may be String, Integer, Float, true/false, or Money

  • anonymous_id (String, nil) (defaults to: nil)

    optional, links to a browser visitor

  • timestamp (Time, String, nil) (defaults to: nil)

    optional; if omitted, uses Time.now.utc

Returns:

  • (true)

Raises:



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/clamp_analytics.rb', line 53

def track(name, properties: {}, anonymous_id: nil, timestamp: nil)
  cfg = @mutex.synchronize { @config }
  raise NotInitializedError, "clamp_analytics: call Clamp::Analytics.init before track" if cfg.nil?

  payload = { p: cfg[:project_id], name: name }
  payload[:anonymousId] = anonymous_id unless anonymous_id.nil?
  payload[:properties] = serialize_properties(properties) unless properties.empty?
  payload[:timestamp] = serialize_timestamp(timestamp)

  response = transport.call(
    "#{cfg[:endpoint]}/e/s",
    { "content-type" => "application/json", "x-clamp-key" => cfg[:api_key] },
    JSON.generate(payload)
  )

  status = response[:status]
  if status < 200 || status >= 300
    raise HTTPError.new(status, response[:body].to_s)
  end

  true
end

.transport=(transport) ⇒ Object

Override the transport. Used by tests; pass nil to restore the default.



77
78
79
# File 'lib/clamp_analytics.rb', line 77

def transport=(transport)
  @mutex.synchronize { @transport = transport }
end