HangarX Ruby SDK

Official Ruby SDK for HangarX - AI-powered Growth OS with analytics, SEO intelligence, and workflow automation.

Features

  • 🚀 Event Tracking - Track user actions, page views, and custom events
  • 🧠 AI-Powered Analytics - Conversational analytics and insights
  • 📊 SEO Intelligence - Real-time SEO insights and recommendations
  • 🔄 Workflow Automation - Execute and monitor multi-agent workflows
  • 📈 Growth Intelligence - AI-driven growth recommendations
  • 🎯 Anomaly Detection - Automatic detection of unusual patterns
  • 💾 Batch Processing - Efficient bulk event handling
  • 🔒 Thread-Safe - Safe for multi-threaded applications
  • High Performance - Optimized for production use

Installation

Add this line to your application's Gemfile:

gem 'hangarx'

And then execute:

bundle install

Or install it yourself as:

gem install hangarx

Quick Start

1. Initialize the Client

require 'hangarx'

hangarx = HangarX::Client.new(
  api_key: 'proj_abc123...', # Your project SDK key (from projects.sdk_key)
  endpoint: 'https://api.hangarx.com'
)

2. Track Events

# Track a user action
hangarx.track(
  user_id: 'user-123',
  event: 'button_clicked',
  properties: {
    button_name: 'signup',
    page: 'landing'
  }
)

# Identify a user
hangarx.identify(
  user_id: 'user-123',
  traits: {
    email: '[email protected]',
    plan: 'premium',
    company: 'Acme Inc'
  }
)

# Track page views
hangarx.page(
  user_id: 'user-123',
  name: 'Landing Page',
  properties: {
    url: 'https://example.com',
    title: 'Welcome'
  }
)

3. Multi-Tenancy Tracking

Track analytics across Organizations, Teams, Client Accounts, and Projects by adding context to your events.

Hierarchy Structure

Organizations (Partners/Agencies)
    
Teams (Collaboration Units)
    
Client Accounts (Business Entities)
    
Projects (Websites/Apps)
    
Events (User Actions)

Adding Multi-Tenancy Context

# Track event with full context
hangarx.track(
  user_id: 'user-123',
  event: 'api_request',
  properties: {
    endpoint: '/api/users',
    method: 'POST',
    response_time: 145,

    # Multi-tenancy context
    organization_id: 'org_marketing_agency',
    team_id: 'team_client_services',
    client_account_id: 'client_acme_corp',
    project_id: 'proj_acme_website'
  }
)

# Identify user with context
hangarx.identify(
  user_id: 'user-123',
  traits: {
    email: '[email protected]',
    name: 'John Doe',

    # Multi-tenancy context
    organization_id: 'org_marketing_agency',
    team_id: 'team_client_services',
    role: 'admin'
  }
)

Use Cases

Partner Agency Managing Multiple Clients:

AGENCY_CONTEXT = {
  organization_id: 'org_marketing_agency',
  team_id: 'team_client_services'
}

# Client 1: E-commerce Store
hangarx.track(
  user_id: 'user-123',
  event: 'product_viewed',
  properties: {
    product_id: 'prod_456',
    **AGENCY_CONTEXT,
    client_account_id: 'client_ecommerce',
    project_id: 'proj_store_website'
  }
)

# Client 2: SaaS Company
hangarx.track(
  user_id: 'user-789',
  event: 'signup_completed',
  properties: {
    plan: 'pro',
    **AGENCY_CONTEXT,
    client_account_id: 'client_saas',
    project_id: 'proj_saas_app'
  }
)

Consultant Managing Client Projects:

CONSULTANT_CONTEXT = {
  team_id: 'team_john_consulting',
  consultant_id: 'user_john'
}

# Client A: Restaurant
hangarx.track(
  user_id: 'visitor-123',
  event: 'reservation_made',
  properties: {
    date: '2025-10-15',
    party_size: 4,
    **CONSULTANT_CONTEXT,
    client_account_id: 'client_restaurant',
    project_id: 'proj_restaurant_site'
  }
)

Helper Module

Create a reusable context module:

module AnalyticsContext
  def self.build(org_id: nil, team_id: nil, client_id: nil, project_id: nil)
    {}.tap do |ctx|
      ctx[:organization_id] = org_id if org_id
      ctx[:team_id] = team_id if team_id
      ctx[:client_account_id] = client_id if client_id
      ctx[:project_id] = project_id if project_id
    end
  end

  def self.track(user_id:, event:, properties: {}, **context_params)
    context = build(**context_params)
    HangarX.track(
      user_id: user_id,
      event: event,
      properties: properties.merge(context)
    )
  end
end

# Usage
AnalyticsContext.track(
  user_id: 'user-123',
  event: 'button_clicked',
  properties: { button: 'signup' },
  org_id: 'org_abc',
  team_id: 'team_xyz',
  client_id: 'client_def',
  project_id: 'proj_ghi'
)

For complete multi-tenancy documentation, see SDK_MULTI_TENANCY_TRACKING.md


4. Use Growth OS Features

# Ask analytics questions
answer = hangarx.ask_analytics(
  'What are my top performing channels this month?'
)

# Get SEO insights
seo_insights = hangarx.seo_insights(
  start_date: '2025-01-01',
  end_date: '2025-01-31'
)

# Detect anomalies
anomalies = hangarx.detect_anomalies(
  start_date: '2025-01-01',
  end_date: '2025-01-31'
)

# Get real-time recommendations
recommendations = hangarx.real_time_recommendations

Configuration

Client Options

hangarx = HangarX::Client.new(
  api_key: 'proj_abc123...',      # Required: Your project SDK key (from projects.sdk_key)
  endpoint: 'https://api.hangarx.com', # Optional: API endpoint
  timeout: 30,                    # Optional: Request timeout in seconds
  retries: 3,                     # Optional: Number of retries
  batch_size: 100,                # Optional: Batch size for bulk operations
  debug: false                    # Optional: Enable debug logging
)

Environment Variables

You can also configure the client using environment variables:

export HANGARX_API_KEY=proj_abc123...  # Your project SDK key
export HANGARX_ENDPOINT=https://api.hangarx.com
# Client will automatically use environment variables
hangarx = HangarX::Client.new

API Reference

Event Tracking

Track Events

Track user actions and behaviors:

hangarx.track(
  user_id: 'user-123',           # Required: User identifier
  event: 'purchase',             # Required: Event name
  properties: {                  # Optional: Event properties
    product_id: 'prod-456',
    revenue: 99.99,
    currency: 'USD',
    category: 'subscription'
  },
  context: {                     # Optional: Additional context
    page: {
      url: 'https://example.com/checkout',
      title: 'Checkout'
    }
  },
  timestamp: Time.now            # Optional: Event timestamp
)

Identify Users

Associate user traits with a user ID:

hangarx.identify(
  user_id: 'user-123',
  traits: {
    email: '[email protected]',
    name: 'John Doe',
    plan: 'premium',
    company: 'Acme Inc',
    created_at: Time.now
  }
)

Page Views

Track page views and navigation:

hangarx.page(
  user_id: 'user-123',
  name: 'Product Page',
  category: 'ecommerce',
  properties: {
    url: 'https://example.com/products/123',
    title: 'Amazing Product',
    referrer: 'https://google.com'
  }
)

Screen Views

Track screen views in mobile applications:

hangarx.screen(
  user_id: 'user-123',
  name: 'Dashboard',
  category: 'app',
  properties: {
    screen_id: 'dashboard_v2',
    version: '2.1.0'
  }
)

Growth OS Features

Ask Analytics

Ask natural language questions about your analytics:

answer = hangarx.ask_analytics(
  'What are my conversion rates by channel?',
  context: { timeframe: 'last_30_days' }
)

Growth Intelligence

Get AI-powered growth insights:

intelligence = hangarx.growth_intelligence(
  start_date: '2025-01-01',
  end_date: '2025-01-31'
)

SEO Insights

Get SEO performance insights:

seo_insights = hangarx.seo_insights(
  start_date: '2025-01-01',
  end_date: '2025-01-31'
)

Anomaly Detection

Detect unusual patterns in your data:

anomalies = hangarx.detect_anomalies(
  start_date: '2025-01-01',
  end_date: '2025-01-31'
)

Real-Time Recommendations

Get real-time personalized recommendations:

recommendations = hangarx.real_time_recommendations(
  session_id: 'session-123'
)

Workflow Management

Execute Workflow

Execute a multi-agent workflow:

result = hangarx.execute_workflow(
  name: 'SEO Audit',
  steps: [
    { agent: 'helix', action: 'analyze_content', params: { url: 'https://example.com' } },
    { agent: 'cortex', action: 'extract_entities', params: { text: '...' } },
    { agent: 'raven', action: 'track_results', params: { metrics: {...} } }
  ]
)

Batch Operations

Batch Events

Send multiple events efficiently:

events = [
  {
    type: 'track',
    user_id: 'user-123',
    event: 'signup',
    properties: { plan: 'free' }
  },
  {
    type: 'track',
    user_id: 'user-123',
    event: 'first_login',
    properties: { timestamp: Time.now }
  }
]

hangarx.batch(events)

Advanced Usage

Error Handling

begin
  hangarx.track(
    user_id: 'user-123',
    event: 'purchase',
    properties: { amount: 99.99 }
  )
rescue HangarX::Error => e
  puts "Failed to track event: #{e.message}"
end

Custom Context

hangarx.track(
  user_id: 'user-123',
  event: 'api_call',
  properties: { endpoint: '/api/users' },
  context: {
    app: {
      name: 'MyApp',
      version: '1.2.3'
    },
    library: {
      name: 'hangarx-ruby',
      version: HangarX::VERSION
    },
    device: {
      type: 'server'
    }
  }
)

Async Processing

# Non-blocking event tracking
hangarx.track_async(
  user_id: 'user-123',
  event: 'background_job_completed',
  properties: { job_id: 'job-456' }
)

Rails Integration

Initializer

Create config/initializers/hangarx.rb:

HangarX.configure do |config|
  config.api_key = ENV['HANGARX_API_KEY']
  config.endpoint = ENV['HANGARX_ENDPOINT']
  config.team_id = ENV['HANGARX_TEAM_ID']
  config.debug = Rails.env.development?
end

Controller Usage

class ApplicationController < ActionController::Base
  before_action :track_page_view

  private

  def track_page_view
    return unless current_user

    HangarX.page(
      user_id: current_user.id,
      name: "#{controller_name}##{action_name}",
      properties: {
        url: request.url,
        user_agent: request.user_agent,
        referrer: request.referrer
      }
    )
  end
end

Model Integration

class User < ApplicationRecord
  after_create :track_signup
  after_update :track_profile_update

  private

  def 
    HangarX.track(
      user_id: id,
      event: 'user_signup',
      properties: {
        email: email,
        plan: plan,
        source: utm_source
      }
    )

    HangarX.identify(
      user_id: id,
      traits: {
        email: email,
        name: name,
        created_at: created_at
      }
    )
  end

  def track_profile_update
    HangarX.track(
      user_id: id,
      event: 'profile_updated',
      properties: {
        fields_changed: saved_changes.keys
      }
    )
  end
end

Background Jobs

class AnalyticsJob < ApplicationJob
  queue_as :default

  def perform(user_id, event, properties = {})
    HangarX.track(
      user_id: user_id,
      event: event,
      properties: properties
    )
  end
end

# Usage
AnalyticsJob.perform_later('user-123', 'purchase', { amount: 99.99 })

Sinatra Integration

require 'sinatra'
require 'hangarx'

configure do
  set :hangarx, HangarX::Client.new(
    api_key: ENV['HANGARX_API_KEY']
  )
end

before do
  settings.hangarx.page(
    user_id: session[:user_id],
    name: request.path,
    properties: {
      url: request.url,
      method: request.request_method
    }
  ) if session[:user_id]
end

post '/signup' do
  user = create_user(params)

  settings.hangarx.identify(
    user_id: user.id,
    traits: {
      email: user.email,
      name: user.name
    }
  )

  settings.hangarx.track(
    user_id: user.id,
    event: 'signup',
    properties: {
      plan: params[:plan],
      source: params[:utm_source]
    }
  )

  redirect '/dashboard'
end

Testing

RSpec Integration

# spec/spec_helper.rb
require 'hangarx'
require 'webmock/rspec'

RSpec.configure do |config|
  config.before(:each) do
    # Stub HangarX API calls in tests
    stub_request(:post, %r{api.hangarx.com})
      .to_return(status: 200, body: '{"success": true}')
  end
end

Test Examples

RSpec.describe 'User tracking' do
  let(:hangarx) { HangarX::Client.new(api_key: 'test-key') }

  it 'tracks user signup' do
    expect {
      hangarx.track(
        user_id: 'user-123',
        event: 'signup',
        properties: { plan: 'free' }
      )
    }.not_to raise_error
  end

  it 'identifies users' do
    expect {
      hangarx.identify(
        user_id: 'user-123',
        traits: { email: '[email protected]' }
      )
    }.not_to raise_error
  end
end

Best Practices

Event Naming

Use clear, descriptive event names:

# ✅ Good
hangarx.track(user_id: 'user-123', event: 'purchase_completed')
hangarx.track(user_id: 'user-123', event: 'signup_form_submitted')

# ❌ Bad
hangarx.track(user_id: 'user-123', event: 'event1')
hangarx.track(user_id: 'user-123', event: 'click')

Property Structure

Keep properties consistent and well-structured:

# ✅ Good
hangarx.track(
  user_id: 'user-123',
  event: 'purchase',
  properties: {
    product_id: 'prod-456',
    product_name: 'Premium Plan',
    revenue: 99.99,
    currency: 'USD',
    category: 'subscription'
  }
)

# ❌ Bad
hangarx.track(
  user_id: 'user-123',
  event: 'purchase',
  properties: {
    prod: 'Premium',
    amount: '99.99',
    type: 'sub'
  }
)

User Identification

Always identify users early:

# On signup
hangarx.identify(
  user_id: user.id,
  traits: {
    email: user.email,
    name: user.name,
    created_at: Time.now
  }
)

# On login
hangarx.identify(
  user_id: user.id,
  traits: {
    last_login: Time.now
  }
)

Performance

The SDK is optimized for high-performance production use:

  • Connection Pooling: Reuses HTTP connections
  • Retry Logic: Exponential backoff for failed requests
  • Thread-Safe: Safe for multi-threaded applications
  • Memory Efficient: Minimal memory footprint
  • Batch Processing: Efficient bulk event handling

Development

Setup

git clone https://github.com/your-org/hangarx-mission-control.git
cd hangarx-mission-control/sdk/hangarx-ruby
bundle install

Running Tests

bundle exec rspec

Code Quality

bundle exec rubocop

Documentation

bundle exec yard doc

Support

Contributing

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -am 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

License

MIT License - see LICENSE for details.


Transform your Ruby applications with AI-powered growth intelligence.