# Product analytics for Rails

Add product analytics to Rails or plain Ruby with the open-source pug-sh gem: events that never raise, safe under Puma and Sidekiq forks, and profile reads.

Source: https://pug.sh/integrations/rails

Send events from Rails or plain Ruby with the pug-sh gem. Every call names the user, since a server has no browser session to infer one from, and the same private key reads profiles and insights back into your own code.

- Pug Ruby SDK: one SDK for Ruby and Rails
- pug-sh
- Open source: MIT SDK, AGPL-3.0 server

## Add Pug to Rails

Four steps, start to first insight. Everything below uses the Ruby SDK exactly as it ships.

### 1. Add the gem

The gem needs Ruby 3.3 or newer and loads as pug, which Bundler.require does for you in Rails.

```bash
bundle add pug-sh
# or, without Bundler: gem install pug-sh
```

### 2. Construct one client at boot

Pug::Client.new raises ArgumentError unless the key starts with prv_, so the guard skips it during assets:precompile in the Dockerfile Rails generates, which boots with SECRET_KEY_BASE_DUMMY=1 and no credentials. The at_exit hook drains the queues on shutdown.

`config/initializers/pug.rb`

```ruby
unless ENV["SECRET_KEY_BASE_DUMMY"]
  PUG = Pug::Client.new(
    api_key: Rails.application.credentials.pug_private_key, # prv_…
    logger: Rails.logger,
  )
  at_exit { PUG.close(timeout: 5) }
end
```

### 3. Track the events you can’t trust a browser for

track takes the user first, as a String or an Integer such as a record’s id, and returns without waiting on the network; invalid input is logged and dropped, so it can sit in a request. A BigDecimal amount goes out as a double.

`app/controllers/orders_controller.rb`

```ruby
class OrdersController < ApplicationController
  def create
    order = Order.create!(order_params)
    PUG.track(current_user.id, "order.completed",
              amount: order.total, currency: "USD")
    redirect_to order
  end
end
```

### 4. Identify people and read the data back

identify writes traits to the profile, and a model callback keeps them current. Reads run in your control flow and raise Pug::Error, whose code is the Connect code as a Symbol, such as :not_found. They are never retried, so the retry policy is yours.

```ruby
class User < ApplicationRecord
  after_save_commit { PUG.identify(id, email: email, plan: plan) }
end

begin
  profile = PUG.profiles.get_by_external_id(user.id.to_s)
rescue Pug::Error => e
  raise unless e.code == :not_found
end
```

## What to watch for in Rails

The specifics that decide whether the numbers you see are the numbers that happened.

### A private key is not a public key

The client SDKs’ key (pub_…) is write-scoped and meant to ship in an app. The server key (prv_…) also reads every profile and insight in the project, so keep it in Rails credentials or an environment variable; Pug::Client.new raises without one.

### Safe across threads and forks

One client serves every thread. A client created before Puma, Unicorn, or Sidekiq forks starts empty in each child, with its own sender threads and connections, so the initializer is safe; events queued in the parent stay with the parent.

### Keys arrive in camelCase

A property or trait key in snake_case is sent in camelCase, so order_total: lands as orderTotal, the spelling well-known event fields use. Reports and reads use the stored name, so filter on orderTotal.

### No location unless you pass it

Pug derives location from CDN headers only on requests made with a public key, so an event from this gem has no geo at all. Pass location: with the visitor’s country and city when a report needs them.

## Product analytics in your Rails app

### Tracking that never raises

track and identify validate, queue and return. Background threads send events and identifies in batches of up to 100 every five seconds, and retry a transient failure.

### Profile traits from your backend

identify writes plan, role, or billing state from the one place that knows them, merged into the traits the profile already has.

### Reads as well as writes

The same private key reads profiles, activity, and insight queries. Responses are the generated messages, and to_h turns one into plain Ruby data.

### Pairs with the client SDKs

Web, mobile, and server events share one timeline per person when they name the same user id.

## Read it in the docs

The Ruby SDK reference goes deeper than a setup page can: every option, every event, and the edge cases.

- [Ruby SDK reference](https://docs.pug.sh/sdks/ruby/): Every option, property type, and delivery rule, with the Rails initializer.
- [Server-side reads](https://docs.pug.sh/sdks/ruby/#server-side-reads): The profiles, activity, and insights methods, and the messages they return.
- [Visitor location](https://docs.pug.sh/sdks/ruby/#visitor-location): The location fields, and what happens to one that looks like a mistake.
- [Well-known events](https://docs.pug.sh/reference/well-known-events/): The event kinds with typed schemas that track checks properties against.
- [Authentication](https://docs.pug.sh/get-started/authentication/): Issuing keys, what each scope allows, and rotation.

* [Start from the beginning](https://docs.pug.sh/get-started/)
* [See all SDKs](https://pug.sh/sdks)

## Pug + Rails: common questions

### Does it need Rails?

No. Rails only adds the initializer. In plain Ruby, require "pug", construct one Pug::Client the same way, and call close before the process exits so nothing queued is lost.

### Does the gem autocapture anything?

No. Autocapture is a browser feature, so you send every server event with track. The server adds no user agent to these events either.

### Is there a consent gate?

No. The Ruby SDK has no consent state and no redaction hooks: check the visitor’s consent choice before you call track, and keep personal data out of the properties you pass.

### What happens to events when a send fails?

A transient failure, such as a network error or a timeout, keeps the batch queued and retries it, no sooner than a second later. A permanent one, such as a rejected key, goes to the on_error hook as a Pug::Error carrying the code. close reports anything it couldn’t send there and to the log.

### Does the AGPL apply to my app?

No. The gem is MIT-licensed; AGPL-3.0 covers the Pug server. Self-host it and set endpoint to your deployment, or use Pug Cloud, free up to 100k events a month.
