To integrate Mixpanel site analytics into your Ruby on Rails project, follow these steps:

  1. Install the mixpanel-ruby gem by adding it to your Gemfile:
gem 'mixpanel-ruby'

Then run bundle install to install the gem.

  1. Create an initializer file to set up the Mixpanel tracker:
# config/initializers/mixpanel.rb
 
require 'mixpanel-ruby'
 
$mixpanel_tracker = Mixpanel::Tracker.new(ENV['MIXPANEL_TOKEN'])

Make sure to set your Mixpanel token as an environment variable[8].

  1. To track events, you can use the tracker in your controllers or models:
class SomeController  'Value1',
      'Property2' => 'Value2'
    })
  end
end
  1. For tracking user profiles, you can use the people method:
$mixpanel_tracker.people.set(user.id, {
  '$first_name' => user.first_name,
  '$last_name' => user.last_name,
  '$email' => user.email
})
  1. To improve performance, consider using background jobs for tracking events:
class TrackEventJob  'Value' })
  1. For more advanced integration, you can use Rails instrumentation to automatically track controller actions[6]:
# app/instruments/process_action_instrument.rb
 
class ProcessActionInstrument
  def call(name, started, finished, unique_id, payload)
    return unless payload[:controller] && payload[:action]
 
    event_name = "#{payload[:controller]}##{payload[:action]}"
    user_id = payload[:current_user]&.id || 'anonymous'
 
    TrackEventJob.perform_later(user_id, event_name, payload.slice(:method, :path, :format, :status))
  end
end
 
# config/initializers/instruments.rb
ActiveSupport::Notifications.subscribe 'process_action.action_controller', ProcessActionInstrument.new

This setup will help you integrate Mixpanel analytics into your Ruby on Rails project, allowing you to track events, user profiles, and automatically log controller actions for better insights into your application’s usage.

resources