analytics-ruby

repository·master·Indexed 18 days ago

https://github.com/segmentio/analytics-ruby

A Ruby client for Segment that allows developers to instrument applications with a single API to send data to downstream analytics tools. It provides the Segment::Analytics client for tracking events (track, identify, page, screen, alias, group) and includes a test queue for verification, a stubbing mode to prevent network calls, and an e2e-cli tool for end-to-end testing of event sequences.

Tokens
4.8K
Snippets
21
Records
25
Agent score
64%

What's inside analytics-ruby

  1. Use the Test Queue for testing

    master

    When initializing Segment::Analytics, you can pass test: true to capture all requests in a local test_queue instead of sending them to Segment. This allows you to inspect sent events during automated tests.

    To prevent real network calls during specs, combine test: true with stub: true.

    Key Test Queue methods:

    • client.test_queue.all: Returns all messages in the queue.
    • client.test_queue.track: Returns only track events.
    • client.test_queue.alias: Returns only alias events.
    • client.test_queue.group: Returns only group events.
    • client.test_queue.identify: Returns only identify events.
    • client.test_queue.page: Returns only page events.
    • client.test_queue.screen: Returns only screen events.
    • client.test_queue.reset!: Clears the queue.
    client = Segment::Analytics.new(write_key: 'YOUR_WRITE_KEY', test: true)
    
    client.track(user_id: 'foo', event: 'bar')
    
    # Inspect the captured event
    client.test_queue.all
    # [
    #     {
    #          :context => { :library => { :name => "analytics-ruby", :version => "2.2.8.pre" } },
    #          :messageId => "e9754cc0-1c5e-47e4-832a-203589d279e4",
    #          :timestamp => "2021-02-19T13:32:39.547+01:00",
    #            :userId => "foo",
    #              :type => "track",
    #               :event => "bar",
    #          :properties => {}
    #     }
    # ]
    
    # Clear the queue for the next test
    client.test_queue.reset!
  2. Use the analytics-ruby e2e-cli for end-to-end testing

    master

    The analytics-ruby e2e-cli is a tool for testing the analytics-ruby SDK by sending event sequences through the real SDK and reporting the outcome as JSON. It accepts a JSON description of event sequences and SDK configuration via the --input flag.

    Requirements

    • Ruby 2.6+
    • The analytics-ruby SDK must be present in the parent directory (the script adds ../lib to $LOAD_PATH automatically).

    Usage

    Run the script using ruby main.rb and provide a JSON string to the --input argument.

    ruby main.rb --input '<json>'
  3. Run the full E2E test suite

    master

    To run the full end-to-end test suite, use the ./run-e2e.sh script.

    Note: This requires the sdk-e2e-tests repository to be checked out alongside the SDK root (at ../../sdk-e2e-tests relative to this directory).

    Commands

    • Standard run: ./run-e2e.sh
    • With custom tests directory: E2E_TESTS_DIR=/path/to/sdk-e2e-tests ./run-e2e.sh
    • Run specific suite: ./run-e2e.sh --suite basic (arguments are forwarded to run-tests.sh)
    ./run-e2e.sh
  4. Configure the e2e-cli input JSON

    master

    The input to the CLI is a JSON object that configures the SDK and defines event sequences.

    Top-level Fields

    FieldTypeDescription
    writeKeystringSegment write key
    apiHoststringFull API base URL (e.g. https://api.segment.io)
    sequencesarrayList of event sequences (processed in order)
    configobjectSDK configuration settings

    Sequence Fields

    Each object in the sequences array contains:

    • delayMs (number): Milliseconds to sleep before processing this sequence.
    • events (array): A list of event objects to send.

    Configuration (config) Fields

    FieldTypeDescription
    flushAtnumberMax events per batch (batch_size)
    flushIntervalnumberFlush interval in ms (informational, not applied)
    maxRetriesnumberNumber of HTTP retries on failure
    timeoutnumberHTTP timeout in seconds (informational, not applied)
  5. Initialize Segment::Analytics with stubbing

    master

    You can initialize the Segment::Analytics module to create a client instance. This module acts as a proxy to Segment::Analytics::Client.

    To prevent requests from hitting the actual Segment server during development or testing, you can pass the :stub option. When :stub is set to true, requests are stubbed to return a successful response without making network calls.

    # To enable stubbing (no network requests)
    analytics = Segment::Analytics.new(stub: true)
    
    # Standard initialization
    analytics = Segment::Analytics.new
  6. Example e2e-cli input JSON

    master

    This example demonstrates a complete configuration including SDK settings, a sequence of different event types, and batching configuration.

    ruby main.rb --input '{
      "writeKey": "YOUR_WRITE_KEY",
      "apiHost": "https://api.segment.io",
      "sequences": [
        {
          "delayMs": 0,
          "events": [
            {"type": "track", "event": "Test Event", "userId": "user-1", "properties": {"foo": "bar"}},
            {"type": "identify", "userId": "user-1", "traits": {"name": "Alice"}},
            {"type": "page", "userId": "user-1", "name": "Home", "category": "Nav"},
            {"type": "screen", "userId": "user-1", "name": "Main"},
            {"type": "alias", "userId": "new-id", "previousId": "user-1"},
            {"type": "group", "userId": "user-1", "groupId": "group-1", "traits": {"plan": "pro"}}
          ]
        }
      ],
      "config": {
        "flushAt": 15,
        "flushInterval": 1000,
        "maxRetries": 3,
        "timeout": 10
      }
    }'
  7. Configure the Segment::Analytics logger

    master

    The Segment::Analytics module provides a centralized logging mechanism. By default, it uses Rails.logger if the Rails framework is defined; otherwise, it initializes a new Logger instance pointing to STDOUT with the program name set to Segment::Analytics.

    All log messages are wrapped by a PrefixedLogger which prepends the string [analytics-ruby] to every message. You can override the global logger by assigning a new logger instance to Segment::Analytics.logger.

    # To use the default logger:
    Segment::Analytics.logger.info("Message")
    
    # To provide a custom logger:
    custom_logger = Logger.new('segment.log')
    Segment::Analytics.logger = custom_logger
  8. Supported event types in e2e-cli

    master

    All event keys in the JSON input must use camelCase. The CLI converts them to snake_case before passing them to the SDK.

    typeRequired keysOptional keys
    trackuserId or anonymousId, eventproperties, context, integrations, messageId, timestamp
    identifyuserId or anonymousIdtraits, context, integrations, messageId, timestamp
    pageuserId or anonymousIdname, category, properties, context, integrations, messageId, timestamp
    screenuserId or anonymousIdname, properties, context, integrations, messageId, timestamp
    aliasuserId, previousIdcontext, integrations, messageId, timestamp
    groupuserId or anonymousId, groupIdtraits, context, integrations, messageId, timestamp