Documentation
Platform Integration/Ruby Integration

Ruby Integration

Spyglasses integrates seamlessly with Ruby web applications through our official gem. The gem provides a Rack middleware that works with Rails, Sinatra, and any other Rack-based Ruby framework.

Installation

  1. Add the gem to your Gemfile:

    gem 'spyglasses'

    Then run:

    bundle install

    Or install directly:

    gem install spyglasses
  2. Set your API key: Add your Spyglasses API key to your environment variables:

    SPYGLASSES_API_KEY=your_api_key_here
    

Rails Integration

Add the middleware to your Rails application in config/application.rb:

# config/application.rb
class Application < Rails::Application
  # Add Spyglasses middleware
  config.middleware.use Spyglasses::Middleware
end

Option 2: Initializer with Configuration

Create an initializer for more control over the configuration:

# config/initializers/spyglasses.rb
Spyglasses.configure do |config|
  config.api_key = ENV['SPYGLASSES_API_KEY']
  config.debug = Rails.env.development?
  config.platform_type = 'rails'
  config.exclude_paths = [
    '/rails/active_storage',  # Exclude Active Storage routes
    '/admin',                 # Exclude admin routes
    %r{^/api/internal}        # Exclude internal API routes (regex)
  ]
end
 
# Add middleware with configuration
Rails.application.config.middleware.use Spyglasses::Middleware

Rails-Specific Considerations

Active Storage: By default, Rails Active Storage routes (/rails/active_storage/*) are automatically excluded from monitoring.

Asset Pipeline: Static assets are automatically excluded, but if you have custom asset routes, add them to exclude_paths.

API-Only Applications: For Rails API applications, the middleware works the same way:

# config/application.rb
class Application < Rails::Application
  config.api_only = true
  config.middleware.use Spyglasses::Middleware
end

Development vs Production: Consider enabling debug mode only in development:

# config/initializers/spyglasses.rb
Spyglasses.configure do |config|
  config.debug = Rails.env.development?
  config.exclude_paths = Rails.env.development? ? ['/debug'] : []
end

Sinatra Integration

For Sinatra applications, add the middleware using the use directive:

# app.rb
require 'sinatra'
require 'spyglasses'
 
# Configure Spyglasses
configure do
  Spyglasses.configure do |config|
    config.api_key = ENV['SPYGLASSES_API_KEY']
    config.platform_type = 'sinatra'
    config.debug = development?
  end
end
 
# Add middleware
use Spyglasses::Middleware
 
get '/' do
  'Hello World!'
end

Sinatra with Options

You can also pass options directly to the middleware:

use Spyglasses::Middleware, {
  api_key: ENV['SPYGLASSES_API_KEY'],
  debug: development?,
  exclude_paths: ['/health', '/metrics']
}

Other Ruby Frameworks

Hanami

# config/environment.rb
Hanami.configure do
  middleware.use Spyglasses::Middleware, api_key: ENV['SPYGLASSES_API_KEY']
end

Roda

# app.rb
require 'roda'
require 'spyglasses'
 
class App < Roda
  use Spyglasses::Middleware, api_key: ENV['SPYGLASSES_API_KEY']
  
  route do |r|
    r.root do
      'Hello World!'
    end
  end
end

Rack Application

For pure Rack applications:

# config.ru
require 'spyglasses'
 
use Spyglasses::Middleware, api_key: ENV['SPYGLASSES_API_KEY']
 
app = lambda do |env|
  [200, {'Content-Type' => 'text/plain'}, ['Hello World!']]
end
 
run app

Configuration Options

The middleware accepts these configuration options:

use Spyglasses::Middleware, {
  api_key: ENV['SPYGLASSES_API_KEY'],     # Required: Your API key
  debug: false,                           # Enable debug logging
  auto_sync: true,                        # Auto-sync patterns on startup
  platform_type: 'rails',                # Platform identifier
  exclude_paths: [                        # Paths to exclude
    '/admin',                             # String matching
    %r{^/api/internal},                   # Regex patterns
    '/health'
  ],
  collect_endpoint: 'https://...',        # Custom collector endpoint
  patterns_endpoint: 'https://...'        # Custom patterns endpoint
}

Environment Variables

Set these environment variables for configuration:

VariableDescriptionDefault
SPYGLASSES_API_KEYYour Spyglasses API keyRequired
SPYGLASSES_DEBUGEnable debug loggingfalse
SPYGLASSES_AUTO_SYNCAuto-sync patterns on startuptrue
SPYGLASSES_CACHE_TTLPattern cache TTL in seconds86400 (24 hours)
SPYGLASSES_COLLECT_ENDPOINTCustom collector endpointhttps://www.spyglasses.io/api/collect
SPYGLASSES_PATTERNS_ENDPOINTCustom patterns endpointhttps://www.spyglasses.io/api/patterns

Deployment

Heroku

Add your API key to Heroku config vars:

heroku config:set SPYGLASSES_API_KEY=your_api_key_here

Docker

Add environment variables to your Dockerfile:

ENV SPYGLASSES_API_KEY=your_api_key_here
ENV SPYGLASSES_DEBUG=false

Or use docker-compose:

services:
  web:
    build: .
    environment:
      - SPYGLASSES_API_KEY=your_api_key_here
      - SPYGLASSES_DEBUG=false

AWS/EC2

Set environment variables in your deployment configuration or use AWS Systems Manager Parameter Store:

export SPYGLASSES_API_KEY=your_api_key_here

DigitalOcean App Platform

Add environment variables in your app configuration:

# .do/app.yaml
name: my-app
services:
- name: web
  environment_slug: ruby
  envs:
  - key: SPYGLASSES_API_KEY
    value: your_api_key_here

Performance Considerations

The Spyglasses middleware is designed for high-performance Ruby applications:

  • Minimal Overhead: Typically under 1ms per request
  • Background Logging: API calls run in background threads
  • Smart Exclusions: Static assets automatically excluded
  • Pattern Caching: Compiled regex patterns are cached

Thread Safety

The middleware is thread-safe and works well with:

  • Puma: Multi-threaded web server
  • Unicorn: Multi-process web server
  • Passenger: Both threading and forking modes

Testing

In your test environment, disable API calls:

# spec/spec_helper.rb or test/test_helper.rb
require 'spyglasses'
 
# Disable API calls in tests
Spyglasses.configure do |config|
  config.api_key = nil
  config.auto_sync = false
end

For RSpec, you might want to stub API calls:

# spec/spec_helper.rb
require 'webmock/rspec'
 
RSpec.configure do |config|
  config.before(:each) do
    stub_request(:get, "https://www.spyglasses.io/api/patterns")
    stub_request(:post, "https://www.spyglasses.io/api/collect")
  end
end

Manual Usage

You can also use Spyglasses outside of the middleware for manual detection:

require 'spyglasses'
 
# Configure the client
client = Spyglasses::Client.new
 
# Detect bots
result = client.detect_bot('GPTBot/1.0')
puts "Bot detected: #{result.is_bot}"
 
# Detect AI referrers  
result = client.detect_ai_referrer('https://chat.openai.com/')
puts "AI referrer: #{result.source_type}"
 
# Combined detection
result = client.detect('Mozilla/5.0', 'https://chat.openai.com/')
puts "Source: #{result.source_type}"

Verifying Installation

After deploying your Ruby application with Spyglasses, verify the installation by:

  1. Check logs for Spyglasses initialization messages (if debug enabled)
  2. Visit your site with different user agents to generate test traffic
  3. Monitor your dashboard at spyglasses.io for incoming data

Enable debug mode temporarily to see detection in action:

# Temporarily enable debug
Spyglasses.configure do |config|
  config.debug = true
end

Troubleshooting

Common Issues

Gem not loading

  • Ensure gem is in your Gemfile and bundle install was run
  • Check for conflicting gems or Ruby version issues

API key not found

  • Verify SPYGLASSES_API_KEY environment variable is set
  • Check for typos in the environment variable name
  • Ensure deployment includes environment variables

Middleware not detecting traffic

  • Verify middleware is properly added to your application
  • Check exclude_paths configuration for overly broad exclusions
  • Enable debug mode to see processing logs

Performance issues

  • Review exclude_paths to ensure static assets are excluded
  • Monitor background thread performance in production
  • Check network latency to Spyglasses endpoints

Rails-specific issues

  • Ensure middleware is added in the correct location
  • Check for conflicts with other middleware (especially authentication)
  • Verify Rails version compatibility (6.0+ recommended)

Debug Mode

Enable debug logging to troubleshoot issues:

Spyglasses.configure do |config|
  config.debug = true
end

This will output detailed logs about:

  • Pattern loading and synchronization
  • Request processing and detection results
  • API communication attempts and responses

Memory Usage

If you notice memory issues:

  • Monitor pattern cache size
  • Check for thread leaks in background logging
  • Consider adjusting cache TTL for frequent pattern updates

Need help? Contact support@spyglasses.io