references/EXAMPLE-ruby-on-rails.md · 24000
ction(t){var e="posthog";return"posthog"!==a&&(e+="."+a),t||(e+=" (stub)"),e},u.people.toString=function(){return u.toString(1)+".people (stub)"},o="init capture register register_once register_for_session unregister unregister_for_session getFeatureFlag getFeatureFlagPayload isFeatureEnabled reloadFeatureFlags updateEarlyAccessFeatureEnrollment getEarlyAccessFeatures on onFeatureFlags onSessionId getSurveys getActiveMatchingSurveys renderSurvey canRenderSurvey identify setPersonProperties group resetGroups setPersonPropertiesForFlags resetPersonPropertiesForFlags setGroupPropertiesForFlags resetGroupPropertiesForFlags reset get_distinct_id getGroups get_session_id get_session_replay_url alias set_config startSessionRecording stopSessionRecording sessionRecordingStarted captureException loadToolbar get_property getSessionProperty createPersonProfile opt_in_capturing opt_out_capturing has_opted_in_capturing has_opted_out_capturing clear_opt_in_out_capturing debug getPageViewId".split(" "),n=0;n<o.length;n++)g(u,o[n]);e._i.push([i,s,a])},e.__SV=1)}(document,window.posthog||[]); posthog.init('<%= ENV["POSTHOG_PROJECT_TOKEN"] %>', { api_host: '<%= ENV.fetch("POSTHOG_HOST", "https://us.i.posthog.com") %>', person_profiles: 'identified_only' })
<div class="container">
<% if flash[:error] %>
<div class="flash error"><%= flash[:error] %></div>
<% end %>
<% if flash[:notice] %>
<div class="flash success"><%= flash[:notice] %></div>
<% end %>
<%= yield %>
</div>
<%= yield :scripts %>
---
## app/views/profiles/show.html.erb
```erb
<% content_for(:title) { 'Profile - PostHog Rails example' } %>
<div class="card">
<h1>Profile</h1>
<p>This page demonstrates error tracking with PostHog and <code>posthog-rails</code>.</p>
</div>
<div class="card">
<h2>User information</h2>
<table style="width: 100%; border-collapse: collapse;">
<tr>
<td style="padding: 10px; border-bottom: 1px solid #eee;"><strong>Email:</strong></td>
<td style="padding: 10px; border-bottom: 1px solid #eee;"><%= current_user.email %></td>
</tr>
<tr>
<td style="padding: 10px; border-bottom: 1px solid #eee;"><strong>Date Joined:</strong></td>
<td style="padding: 10px; border-bottom: 1px solid #eee;"><%= current_user.created_at %></td>
</tr>
<tr>
<td style="padding: 10px;"><strong>Staff Status:</strong></td>
<td style="padding: 10px;"><%= current_user.is_staff ? 'Yes' : 'No' %></td>
</tr>
</table>
</div>
<div class="card">
<h2>Error tracking demo</h2>
<p>Click the buttons below to trigger different types of errors and see how PostHog captures them.</p>
<div style="margin-top: 20px;">
<button class="danger" onclick="triggerError('manual')">
Manual capture_exception
</button>
<button class="danger" onclick="triggerError('rails')" style="margin-left: 10px;">
Rails.error.handle
</button>
</div>
<div id="error-result" style="margin-top: 20px; display: none;"></div>
</div>
<div class="card">
<h3>How error tracking works</h3>
<p><strong>Auto-capture (no code needed):</strong></p>
<pre style="background: #f3f4f6; padding: 15px; border-radius: 5px; overflow-x: auto;"><code># config/initializers/posthog.rb
PostHog::Rails.configure do |config|
config.auto_capture_exceptions = true
config.capture_user_context = true
end
# That's it! Unhandled exceptions are captured automatically.</code></pre>
<p style="margin-top: 15px;"><strong>Manual capture:</strong></p>
<pre style="background: #f3f4f6; padding: 15px; border-radius: 5px; overflow-x: auto;"><code>begin
risky_operation
rescue => e
PostHog.capture_exception(e, user.posthog_distinct_id)
end</code></pre>
<p style="margin-top: 15px;"><strong>Rails.error integration:</strong></p>
<pre style="background: #f3f4f6; padding: 15px; border-radius: 5px; overflow-x: auto;"><code># posthog-rails subscribes to Rails.error automatically
Rails.error.handle(context: { user_id: user.id }) do
risky_operation
end</code></pre>
</div>
<% content_for :scripts do %>
<script>
async function triggerError(type) {
const resultDiv = document.getElementById('error-result');
const url = type === 'rails' ? '/api/test-rails-error' : '/api/test-error';
try {
const response = await fetch(url, {
method: 'POST',
headers: {
'X-CSRF-Token': document.querySelector('meta[name="csrf-token"]').content,
'Content-Type': 'application/json',
},
});
const data = await response.json();
resultDiv.style.display = 'block';
if (data.success) {
resultDiv.innerHTML = '<div class="flash success">' + data.message + '</div>';
} else {
resultDiv.innerHTML = '<div class="flash error"><strong>Error captured:</strong> ' + data.error + '<br><small>' + data.message + '</small></div>';
}
} catch (error) {
resultDiv.style.display = 'block';
resultDiv.innerHTML = '<div class="flash error">Request failed: ' + error + '</div>';
}
}
</script>
<% end %>
app/views/registrations/new.html.erb
<% content_for(:title) { 'Sign Up - PostHog Rails example' } %>
<div class="card">
<h1>Sign Up</h1>
<p>Create an account to see PostHog analytics in action.</p>
<form action="<%= signup_path %>" method="post" style="margin-top: 20px;">
<%= hidden_field_tag :authenticity_token, form_authenticity_token %>
<input type="email" name="email" placeholder="Email" required>
<input type="password" name="password" placeholder="Password" required>
<input type="password" name="password_confirmation" placeholder="Confirm Password" required>
<button type="submit">Sign Up</button>
</form>
<p style="margin-top: 15px; color: #666; font-size: 14px;">
Already have an account? <a href="<%= login_path %>">Login</a>
</p>
</div>
app/views/sessions/new.html.erb
<% content_for(:title) { 'Login - PostHog Rails example' } %>
<div class="card">
<h1>PostHog Rails example</h1>
<p>Welcome! This example demonstrates PostHog integration with Ruby on Rails, including automatic error tracking via <code>posthog-rails</code>.</p>
</div>
<div class="card">
<h2>Login</h2>
<p>Login to see PostHog analytics in action.</p>
<form action="<%= login_path %>" method="post" style="margin-top: 20px;">
<%= hidden_field_tag :authenticity_token, form_authenticity_token %>
<input type="email" name="email" placeholder="Email" required>
<input type="password" name="password" placeholder="Password" required>
<button type="submit">Login</button>
</form>
<p style="margin-top: 15px; color: #666; font-size: 14px;">
Don't have an account? <a href="<%= signup_path %>">Sign up</a><br>
Tip: Run <code>bin/rails db:seed</code> to create [email protected] / admin
</p>
</div>
<div class="card">
<h3>What this example demonstrates</h3>
<ul style="padding-left: 20px;">
<li><strong>User identification</strong> — Users are identified with <code>PostHog.identify</code> on login</li>
<li><strong>Event tracking</strong> — Custom events captured with <code>PostHog.capture</code></li>
<li><strong>Feature flags</strong> — Conditional features with <code>PostHog.is_feature_enabled</code></li>
<li><strong>Error tracking (auto)</strong> — Unhandled exceptions captured automatically by <code>posthog-rails</code></li>
<li><strong>Error tracking (manual)</strong> — Handled errors captured with <code>PostHog.capture_exception</code></li>
<li><strong>ActiveJob instrumentation</strong> — Background job failures captured automatically</li>
<li><strong>Rails.error integration</strong> — Rails 7+ error reporting captured by <code>posthog-rails</code></li>
<li><strong>Frontend tracking</strong> — posthog-js captures pageviews and session replay</li>
</ul>
</div>
bin/rails
#!/usr/bin/env ruby
APP_PATH = File.expand_path('../config/application', __dir__)
require_relative '../config/boot'
require 'rails/commands'
config.ru
require_relative 'config/environment'
run Rails.application
config/application.rb
require_relative 'boot'
require 'rails/all'
Bundler.require(*Rails.groups)
module PosthogExample
class Application < Rails::Application
config.load_defaults 7.1
# Use SQLite for all stores
config.active_job.queue_adapter = :async
end
end
config/boot.rb
ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../Gemfile', __dir__)
require 'bundler/setup'
config/environment.rb
require_relative 'application'
Rails.application.initialize!
config/environments/development.rb
require 'active_support/core_ext/integer/time'
Rails.application.configure do
config.enable_reloading = true
config.eager_load = false
config.consider_all_requests_local = true
config.server_timing = true
# Secret key for development (not used in production)
config.secret_key_base = 'dev-secret-key-for-posthog-example-only'
config.action_controller.perform_caching = false
config.cache_store = :memory_store
config.active_support.deprecation = :log
config.active_support.disallowed_deprecation = :raise
config.active_support.disallowed_deprecation_warnings = []
config.active_record.migration_error = :page_load
config.active_record.verbose_query_logs = true
end
config/initializers/posthog.rb
# PostHog configuration with posthog-rails auto-instrumentation
#
# The posthog-rails gem provides:
# - Automatic exception capture for unhandled controller errors
# - ActiveJob instrumentation for background job failures
# - User context detection from current_user
# - Rails.error integration for rescued exceptions
PostHog.init do |config|
config.api_key = ENV.fetch('POSTHOG_PROJECT_TOKEN', nil)
config.host = ENV.fetch('POSTHOG_HOST', 'https://us.i.posthog.com')
end
PostHog::Rails.configure do |config|
# Auto-capture unhandled exceptions in controllers
config.auto_capture_exceptions = true
# Also capture exceptions that Rails rescues (e.g. ActiveRecord::RecordNotFound)
config.report_rescued_exceptions = true
# Auto-instrument ActiveJob failures
config.auto_instrument_active_job = true
# Automatically associate errors with the current user
config.capture_user_context = true
config.current_user_method = :current_user
config.user_id_method = :posthog_distinct_id
end
config/routes.rb
Rails.application.routes.draw do
# Auth
get 'login', to: 'sessions#new'
post 'login', to: 'sessions#create'
delete 'logout', to: 'sessions#destroy'
get 'signup', to: 'registrations#new'
post 'signup', to: 'registrations#create'
# App
get 'dashboard', to: 'dashboard#show'
get 'burrito', to: 'burritos#show'
post 'api/burrito/consider', to: 'burritos#consider'
get 'profile', to: 'profiles#show'
# Error tracking demos
post 'api/test-error', to: 'errors#test'
post 'api/test-rails-error', to: 'errors#test_rails_error'
# Background job demo
post 'api/test-job', to: 'dashboard#enqueue_test_job'
root 'sessions#new'
end
db/migrate/20240101000000_create_users.rb
class CreateUsers < ActiveRecord::Migration[7.1]
def change
create_table :users do |t|
t.string :email, null: false
t.string :password_digest, null: false
t.boolean :is_staff, default: false
t.timestamps
end
add_index :users, :email, unique: true
end
end
db/schema.rb
# This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# This file is the source Rails uses to define your schema when running `bin/rails
# db:schema:load`. When creating a new database, `bin/rails db:schema:load` tends to
# be faster and is potentially less error prone than running all of your
# migrations from scratch. Old migrations may fail to apply correctly if those
# migrations use external dependencies or application code.
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema[7.2].define(version: 2024_01_01_000000) do
create_table "users", force: :cascade do |t|
t.string "email", null: false
t.string "password_digest", null: false
t.boolean "is_staff", default: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["email"], name: "index_users_on_email", unique: true
end
end
db/seeds.rb
# Create a default admin user for testing
User.find_or_create_by!(email: '[email protected]') do |user|
user.password = 'admin'
user.password_confirmation = 'admin'
user.is_staff = true
end
puts 'Seed data created: [email protected] / admin'
Gemfile
source 'https://rubygems.org'
gem 'rails', '~> 7.1'
gem 'sqlite3', '~> 1.7'
gem 'puma', '~> 6.0'
gem 'bcrypt', '~> 3.1'
gem 'dotenv-rails', '~> 3.0'
# PostHog
gem 'posthog-ruby', '~> 3.0'
gem 'posthog-rails'
Rakefile
require_relative 'config/application'
Rails.application.load_tasks