### Install posthog-ruby Gem Source: https://posthog.com/docs/libraries/ruby/index Add the posthog-ruby gem to your application's Gemfile to enable PostHog tracking functionality. This is the first step before initializing the client. ```bash gem "posthog-ruby" ``` -------------------------------- ### Initialize PostHog Client for Local Evaluation in Puma Server Source: https://posthog.com/docs/libraries/ruby/index This code demonstrates initializing the PostHog client using the `on_worker_boot` hook in a Puma server configuration. This setup is recommended for multi-worker Puma environments to enable local feature flag evaluation, ensuring each worker has an updated feature flag cache. ```ruby on_worker_boot do $posthog = PostHog::Client.new( api_key: '', personal_api_key: '' host: 'https://us.i.posthog.com', on_error: Proc.new { |status, msg| print msg } ) end ``` -------------------------------- ### Handle Feature Flag with Error Handling in Ruby Source: https://posthog.com/docs/libraries/ruby/index This snippet demonstrates how to check if a feature flag is enabled for a given user and includes error handling for cases where the feature flag check might fail. It uses a try-rescue block to catch exceptions and implement fallback logic. This is a basic usage example for feature flags. ```ruby try flag_enabled = handle_feature_flag(client, 'new-feature', 'user-123') if flag_enabled # Implement new feature logic else # Implement old feature logic end rescue => e # Handle the error at a higher level puts 'Feature flag check failed, using default behavior' # Implement fallback logic end ``` -------------------------------- ### Customize Exception Fingerprints with PostHog Ruby Source: https://posthog.com/docs/libraries/ruby/index This example shows how to override the default exception grouping mechanism in PostHog using custom fingerprints. By setting the '$exception_fingerprint' property within the `properties` hash passed to `capture_exception`, you can control how similar exceptions are grouped together in your PostHog project. ```ruby posthog.capture_exception( e, distinct_id: 'user_distinct_id', properties: { '$exception_fingerprint': 'CustomExceptionGroup' } ) ``` -------------------------------- ### Override Server and Group Properties for Feature Flag Evaluation (Ruby) Source: https://posthog.com/docs/libraries/ruby/index This example shows how to override server-side person and group properties when evaluating feature flags using the PostHog Ruby SDK. It's useful for dynamic evaluations based on data not yet ingested or for specific testing scenarios. The `person_properties`, `groups`, and `group_properties` arguments enable this. ```ruby posthog.get_feature_flag( 'flag-key', 'distinct_id_of_the_user', person_properties: { 'property_name': 'value' }, groups: { 'your_group_type': 'your_group_id', 'another_group_type': 'your_group_id', }, group_properties: { 'your_group_type': { 'group_property_name': 'value' } 'another_group_type': { 'group_property_name': 'value' } }, ) ``` -------------------------------- ### Get Multivariate Feature Flag Variant Source: https://posthog.com/docs/libraries/ruby/index Retrieves the specific variant key for a multivariate feature flag assigned to a user. This allows for different user experiences based on flag configuration. It also supports fetching the payload associated with the matched variant. ```ruby enabled_variant = posthog.get_feature_flag('flag-key', 'distinct_id_of_your_user') if enabled_variant == 'variant-key' # replace 'variant-key' with the key of your variant # Do something differently for this user # Optional: fetch the payload matched_flag_payload = posthog.get_feature_flag_payload('variant-key', 'distinct_id_of_your_user') end ``` -------------------------------- ### Run an Experiment (A/B Test) using Feature Flags in Ruby Source: https://posthog.com/docs/libraries/ruby/index This Ruby code snippet illustrates how to run an A/B test by retrieving a feature flag that represents an experiment. It checks the returned variant and executes specific logic based on whether the user is in the control or a specific variant group. This assumes the feature flag is configured to manage experiment variants. ```ruby variant = posthog.get_feature_flag('experiment-feature-flag-key', 'user_distinct_id') if variant == 'variant-name' # Do something end ``` -------------------------------- ### Initialize PostHog Client for Local Evaluation in Unicorn Server Source: https://posthog.com/docs/libraries/ruby/index This code snippet shows how to initialize the PostHog client within the `after_fork` hook of a Unicorn server configuration. This is crucial for enabling local feature flag evaluation by ensuring the client is set up correctly in each forked worker process to receive feature flag updates. ```ruby after_fork do |server, worker| $posthog = PostHog::Client.new( api_key: '', personal_api_key: '' host: 'https://us.i.posthog.com', on_error: Proc.new { |status, msg| print msg } ) end ``` -------------------------------- ### Initialize PostHog Ruby Client Source: https://posthog.com/docs/libraries/ruby/index Initialize the PostHog client with your API key and host. The `on_error` callback can be used to handle errors during API calls. Ensure the host includes the protocol (e.g., `https://`). ```ruby require 'posthog' posthog = PostHog::Client.new({ api_key: "", host: "https://us.i.posthog.com", on_error: Proc.new { |status, msg| print msg } }) ``` -------------------------------- ### Fetch All Feature Flags and Payloads for a User Source: https://posthog.com/docs/libraries/ruby/index Retrieves all feature flag statuses and their associated payloads for a given user in a single call. This is an optimization to avoid multiple individual requests when flag statuses are needed in bulk. ```ruby posthog.get_all_flags('distinct_id_of_your_user') posthog.get_all_flags_and_payloads('distinct_id_of_your_user') ``` -------------------------------- ### Capture Event with Properties in Ruby Source: https://posthog.com/docs/libraries/ruby/index Enhance captured events by including additional information in the `properties` object. This allows for more detailed analysis of user behavior. ```ruby posthog.capture({ distinct_id: 'distinct_id_of_the_user', event: 'user_signed_up', properties: { login_type: 'email', is_free_trial: true } }) ``` -------------------------------- ### Send Pageview Event from Backend in Ruby Source: https://posthog.com/docs/libraries/ruby/index If implementing PostHog solely on the backend, you can send `$pageview` events. This requires specifying the `$current_url` property. ```ruby posthog.capture({ distinct_id: 'distinct_id_of_the_user', event: '$pageview', properties: { '$current_url': 'https://example.com' } }) ``` -------------------------------- ### Implement Error Handling for PostHog Feature Flag Operations in Ruby Source: https://posthog.com/docs/libraries/ruby/index This Ruby function shows how to safely handle potential errors during PostHog feature flag retrieval using a `begin-rescue` block. It logs any exceptions encountered, allowing for graceful failure or the implementation of default flag behaviors. ```ruby def handle_feature_flag(client, flag_key, distinct_id) begin is_enabled = client.is_feature_enabled(flag_key, distinct_id) puts "Feature flag '#{flag_key}' for user '#{distinct_id}' is #{is_enabled ? 'enabled' : 'disabled'}" return is_enabled rescue => e puts "Error fetching feature flag '#{flag_key}': #{e.message}" # Optionally, you can return a default value or throw the error # return false # Default to disabled raise e end end ``` -------------------------------- ### Capture Exceptions Manually with PostHog Ruby Source: https://posthog.com/docs/libraries/ruby/index This snippet demonstrates how to manually capture exceptions using the `posthog-ruby` library. It wraps potentially problematic code in a begin-rescue block and uses `posthog.capture_exception` to send the exception details to PostHog. The method accepts the exception object, an optional distinct ID, and optional properties. ```ruby begin # Code that might raise an exception raise StandardError, "Something went wrong" rescue => e posthog.capture_exception( e, distinct_id: 'user_distinct_id', properties: { custom_property: 'custom_value' } ) end ``` -------------------------------- ### Capture Basic Event in Ruby Source: https://posthog.com/docs/libraries/ruby/index Send a custom event to PostHog using the `capture` method. This requires a `distinct_id` and an `event` name. Event names should follow a `[object] [verb]` format. ```ruby posthog.capture({ distinct_id: 'distinct_id_of_the_user', event: 'user_signed_up' }) ``` -------------------------------- ### Capture Event Sending All Feature Flags Source: https://posthog.com/docs/libraries/ruby/index Includes all relevant feature flag information with a captured event by setting `send_feature_flags` to `true`. This simplifies analytics by automatically attributing flags to events without manual property mapping. This parameter is false by default. ```ruby posthog.capture({ distinct_id: 'distinct_id_of_your_user', event: 'event_name', send_feature_flags: true, }) ``` -------------------------------- ### Capture Event with Granular Feature Flag Control (v3.1.0+) Source: https://posthog.com/docs/libraries/ruby/index Provides advanced control over feature flag inclusion with events using a hash for `send_feature_flags`. Allows specifying local evaluation preferences, person properties, and group properties for evaluation context. ```ruby posthog.capture({ distinct_id: 'distinct_id_of_your_user', event: 'event_name', send_feature_flags: { only_evaluate_locally: true, person_properties: { plan: 'premium' }, group_properties: { org: { tier: 'enterprise' } } } }) ``` -------------------------------- ### Set Person Properties with Capture in Ruby Source: https://posthog.com/docs/libraries/ruby/index Set or update person profile properties when capturing an event using the `$set` and `$set_once` keys within the `properties` object. `$set` updates the property, while `$set_once` only sets it if it doesn't exist. ```ruby posthog.capture( distinct_id: 'distinct_id', event: 'event_name', properties: { '$set': { name: 'Max Hedgehog' }, '$set_once': { initial_url: '/blog' } } ) ``` -------------------------------- ### Alias Distinct IDs in Ruby Source: https://posthog.com/docs/libraries/ruby/index Use the `alias` method to associate multiple distinct IDs with a single user. This is useful when a frontend distinct ID is not available on the backend. ```ruby posthog.alias( distinct_id: "distinct_id", alias: "alias_id" ) ``` -------------------------------- ### Configure Feature Flag Request Timeout in PostHog Ruby Client Source: https://posthog.com/docs/libraries/ruby/index This code demonstrates how to set a custom request timeout for feature flag evaluations when initializing the PostHog Ruby client. This prevents operations from blocking indefinitely if the PostHog servers are slow to respond. The `feature_flag_request_timeout_seconds` parameter controls this, with a default of 3 seconds. ```ruby posthog = PostHog::Client.new({ # rest of your configuration... feature_flag_request_timeout_seconds: 3 # Time in seconds. Default is 3. }) ``` -------------------------------- ### Capture Anonymous Event in Ruby Source: https://posthog.com/docs/libraries/ruby/index Capture events without creating or associating them with person profiles by setting the `$process_person_profile` property to `false`. ```ruby posthog.capture( distinct_id: 'distinct_id', event: 'event_name', properties: { '$process_person_profile': false } ) ``` -------------------------------- ### Capture Group Analytics Event in Ruby Source: https://posthog.com/docs/libraries/ruby/index This code captures an event and associates it with a specific group using PostHog's group analytics feature. It includes the user's distinct ID, event name, event properties, and a group identifier. This functionality is useful for analyzing user behavior at an organizational or team level. ```ruby posthog.capture({ distinct_id: 'distinct_id_of_the_user', event: 'movie_played', properties: { movie_id: '123', category: 'romcom' } groups: { 'company': 'company_id_in_your_db' } }) ``` -------------------------------- ### Check Boolean Feature Flag Status Source: https://posthog.com/docs/libraries/ruby/index Determines if a specific feature flag is enabled for a given user. Optionally retrieves the flag's payload if enabled. This function is essential for conditional logic based on feature availability. ```ruby is_my_flag_enabled = posthog.is_feature_enabled('flag-key', 'distinct_id_of_your_user') if is_my_flag_enabled # Do something differently for this user # Optional: fetch the payload matched_flag_payload = posthog.get_feature_flag_payload('flag-key', 'distinct_id_of_your_user') end ``` -------------------------------- ### Capture Event with Specific Feature Flag Property Source: https://posthog.com/docs/libraries/ruby/index Associates a feature flag with a captured event by including a property in the event's payload. This is crucial for breaking down or filtering events in PostHog insights based on feature flag status. Requires server-side SDKs or API. ```ruby posthog.capture({ distinct_id: 'distinct_id_of_your_user', event: 'event_name', properties: { '$feature/feature-flag-key': 'variant-key', # replace feature-flag-key with your flag key. Replace 'variant-key' with the key of your variant } }) ``` -------------------------------- ### Update Group Properties in Ruby Source: https://posthog.com/docs/libraries/ruby/index This snippet demonstrates how to update properties for a specific group in PostHog. It allows you to associate metadata with groups, such as company names or subscription tiers, which can then be used for segmentation and analysis. The `name` property is special and used for display in the PostHog UI. ```ruby posthog.group_identify( { group_type: "company", group_key: "company_id_in_your_db", properties: { name: "Awesome Inc." } } ) ``` -------------------------------- ### Send $feature_flag_called Events with PostHog Ruby SDK Source: https://posthog.com/docs/libraries/ruby/index This code snippet demonstrates how to explicitly send '$feature_flag_called' events when checking feature flags. It ensures PostHog tracks flag access, providing analytics. The `send_feature_flag_events` argument controls this behavior, defaulting to true under certain conditions. ```ruby is_my_flag_enabled = posthog.is_feature_enabled( 'flag-key', 'distinct_id_of_your_user', send_feature_flag_events: true ) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.