Class: Boxcars::PosthogBackend
- Inherits:
-
Object
- Object
- Boxcars::PosthogBackend
- Includes:
- ObservabilityBackend
- Defined in:
- lib/boxcars/observability_backends/posthog_backend.rb
Overview
An observability backend for sending events to PostHog.
This backend requires the ‘posthog-ruby` gem. Add `gem ’posthog-ruby’‘ to your Gemfile to use this backend.
Example Usage:
require 'boxcars/observability_backends/posthog_backend'
require 'posthog'
client = PostHog::Client.new(
api_key: 'YOUR_POSTHOG_API_KEY',
host: 'https://app.posthog.com' # or your self-hosted instance
)
Boxcars::Observability.backend = Boxcars::PosthogBackend.new(client: client)
# To track user-specific events, ensure :user_id is present in properties
Boxcars::Observability.track(
event: 'my_event',
properties: { user_id: 'user_123', custom_data: 'value' }
)
Instance Method Summary collapse
-
#current_user_id ⇒ Object
in Rails, this is a way to find the current user id.
-
#flush ⇒ Object
Flushes any pending events to PostHog immediately.
-
#initialize(client:) ⇒ PosthogBackend
constructor
Initializes the PosthogBackend.
-
#track(event:, properties:) ⇒ Object
Tracks an event with PostHog.
Constructor Details
#initialize(client:) ⇒ PosthogBackend
Initializes the PosthogBackend. Accepts a pre-configured PostHog client instance.
33 34 35 36 37 38 39 40 41 |
# File 'lib/boxcars/observability_backends/posthog_backend.rb', line 33 def initialize(client:) begin require 'posthog' rescue LoadError raise LoadError, "The 'posthog-ruby' gem is required to use PosthogBackend. Please add it to your Gemfile." end @posthog_client = client end |
Instance Method Details
#current_user_id ⇒ Object
in Rails, this is a way to find the current user id
67 68 69 70 71 |
# File 'lib/boxcars/observability_backends/posthog_backend.rb', line 67 def current_user_id return unless defined?(::Current) && ::Current.respond_to?(:user) ::Current.user&.id end |
#flush ⇒ Object
Flushes any pending events to PostHog immediately. This is useful for testing or when you need to ensure events are sent before the process exits.
62 63 64 |
# File 'lib/boxcars/observability_backends/posthog_backend.rb', line 62 def flush @posthog_client.flush if @posthog_client.respond_to?(:flush) end |
#track(event:, properties:) ⇒ Object
Tracks an event with PostHog.
The ‘:user_id` property is used as PostHog’s ‘distinct_id`. If not provided, events might be tracked anonymously or associated with a default/server ID depending on PostHog’s SDK behavior.
All other properties are passed as event properties to PostHog.
54 55 56 57 58 |
# File 'lib/boxcars/observability_backends/posthog_backend.rb', line 54 def track(event:, properties:) properties = {} unless properties.is_a?(Hash) distinct_id = properties.delete(:user_id) || current_user_id || "anonymous_user" @posthog_client.capture(distinct_id:, event:, properties:) end |