# 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**:
   ```ruby
   gem 'spyglasses'
   ```

   Then run:
   ```bash
   bundle install
   ```

   Or install directly:
   ```bash
   gem install spyglasses
   ```

2. **Set your API key**:
   Add your Spyglasses API key to your environment variables:
   ```env
   SPYGLASSES_API_KEY=your_api_key_here
   ```

## Rails Integration

### Option 1: Application Configuration (Recommended)

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

```ruby
# 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:

```ruby
# 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:

```ruby
# 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:

```ruby
# 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:

```ruby
# 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:

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

## Other Ruby Frameworks

### Hanami

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

### Roda

```ruby
# 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:

```ruby
# 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:

```ruby
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:

| Variable | Description | Default |
|----------|-------------|---------|
| `SPYGLASSES_API_KEY` | Your Spyglasses API key | Required |
| `SPYGLASSES_DEBUG` | Enable debug logging | `false` |
| `SPYGLASSES_AUTO_SYNC` | Auto-sync patterns on startup | `true` |
| `SPYGLASSES_CACHE_TTL` | Pattern cache TTL in seconds | `86400` (24 hours) |
| `SPYGLASSES_COLLECT_ENDPOINT` | Custom collector endpoint | `https://www.spyglasses.io/api/collect` |
| `SPYGLASSES_PATTERNS_ENDPOINT` | Custom patterns endpoint | `https://www.spyglasses.io/api/patterns` |

## Deployment

### Heroku

Add your API key to Heroku config vars:

```bash
heroku config:set SPYGLASSES_API_KEY=your_api_key_here
```

### Docker

Add environment variables to your Dockerfile:

```dockerfile
ENV SPYGLASSES_API_KEY=your_api_key_here
ENV SPYGLASSES_DEBUG=false
```

Or use docker-compose:

```yaml
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:

```bash

```

### DigitalOcean App Platform

Add environment variables in your app configuration:

```yaml
# .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:

```ruby
# 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:

```ruby
# 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:

```ruby
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](https://www.spyglasses.io) for incoming data

Enable debug mode temporarily to see detection in action:

```ruby
# 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:

```ruby
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
