Simple, powerful, first-party analytics for Rails
:fire: Simple, powerful, first-party analytics for Rails
Track visits and events in Ruby, JavaScript, and native apps. Data is stored in your database by default, and you can customize it for any data store as you grow.
:postbox: Check out Ahoy Email for emails and Field Test for A/B testing
:tangerine: Battle-tested at Instacart
Add this line to your application’s Gemfile:
gem "ahoy_matey"And run:
bundle install
rails generate ahoy:install
rails db:migrateRestart your web server, open a page in your browser, and a visit will be created :tada:
Track your first event from a controller with:
ahoy.track "My first event", language: "Ruby"Enable the API in config/initializers/ahoy.rb:
Ahoy.api = trueAnd restart your web server.
For Importmap (Rails default), add to config/importmap.rb:
pin "ahoy", to: "ahoy.js"And add to app/javascript/application.js:
import "ahoy"For Bun, esbuild, rollup.js, or Webpack, run:
bun add ahoy.js
# or
yarn add ahoy.jsAnd add to app/javascript/application.js:
import ahoy from "ahoy.js"For Sprockets, add to app/assets/javascripts/application.js:
//= require ahoyTrack an event with:
ahoy.track("My second event", {language: "JavaScript"});Check out Ahoy iOS and Ahoy Android.
To enable geocoding, see the Geocoding section.
Ahoy provides a number of options to help with GDPR compliance. See the GDPR section for more info.
When someone visits your website, Ahoy creates a visit with lots of useful information.
Use the current_visit method to access it.
Prevent certain Rails actions from creating visits with:
skip_before_action :track_ahoy_visitThis is typically useful for APIs. If your entire Rails app is an API, you can use:
Ahoy.api_only = trueYou can also defer visit tracking to JavaScript. This is useful for preventing bots (that aren’t detected by their user agent) and users with cookies disabled from creating a new visit on each request. :when_needed will create visits server-side only when needed by events, and false will disable server-side creation completely, discarding events without a visit.
Ahoy.server_side_visits = :when_neededEach event has a name and properties. There are several ways to track events.
ahoy.track "Viewed book", title: "Hot, Flat, and Crowded"Track actions automatically with:
class ApplicationController < ActionController::Base
after_action :track_action
protected
def track_action
ahoy.track "Ran action", request.path_parameters
end
endahoy.track("Viewed book", {title: "The World is Flat"});See Ahoy.js for a complete list of features.
See the docs for Ahoy iOS and Ahoy Android.
<head>
<script async custom-element="amp-analytics" src="https://cdn.ampproject.org/v0/amp-analytics-0.1.js"></script>
</head>
<body>
<%= amp_event "Viewed article", title: "Analytics with Rails" %>
</body>Say we want to associate orders with visits. Just add visitable to the model.
class Order < ApplicationRecord
visitable :ahoy_visit
endWhen a visitor places an order, the ahoy_visit_id column is automatically set :tada:
See where orders are coming from with simple joins:
Order.joins(:ahoy_visit).group("referring_domain").count
Order.joins(:ahoy_visit).group("city").count
Order.joins(:ahoy_visit).group("device_type").countHere’s what the migration to add the ahoy_visit_id column should look like:
class AddAhoyVisitToOrders < ActiveRecord::Migration[8.1]
def change
add_reference :orders, :ahoy_visit
end
endCustomize the column with:
visitable :sign_up_visitAhoy automatically attaches the current_user to the visit. With Devise, it attaches the user even if they sign in after the visit starts.
With other authentication frameworks, add this to the end of your sign in method:
ahoy.authenticate(user)To see the visits for a given user, create an association:
class User < ApplicationRecord
has_many :visits, class_name: "Ahoy::Visit"
endAnd use:
User.find(123).visitsUse a method besides current_user
Ahoy.user_method = :true_useror use a proc
Ahoy.user_method = ->(controller) { controller.true_user }To attach the user with Doorkeeper, be sure you have a current_resource_owner method in ApplicationController.
class ApplicationController < ActionController::Base
private
def current_resource_owner
User.find(doorkeeper_token.resource_owner_id) if doorkeeper_token
end
endBots are excluded from tracking by default. To include them, use:
Ahoy.track_bots = trueAdd your own rules with:
Ahoy.exclude_method = lambda do |controller, request|
request.ip == "192.168.1.1"
endBy default, a new visit is created after 4 hours of inactivity. Change this with:
Ahoy.visit_duration = 30.minutesBy default, a new visitor_token is generated after 2 years. Change this with:
Ahoy.visitor_duration = 30.daysTo track visits across multiple subdomains, use:
Ahoy.cookie_domain = :allSet other cookie options with:
Ahoy.cookie_options = {same_site: :lax}You can also disable cookies
Ahoy uses random UUIDs for visit and visitor tokens by default, but you can use your own generator like ULID.
Ahoy.token_generator = -> { ULID.generate }You can use Rack::Attack to throttle requests to the API.
class Rack::Attack
throttle("ahoy/ip", limit: 20, period: 1.minute) do |req|
if req.path.start_with?("/ahoy/")
req.ip
end
end
endExceptions are rescued so analytics do not break your app. Ahoy uses Safely to try to report them to a service by default. To customize this, use:
Safely.report_exception_method = ->(e) { Rollbar.error(e) }Ahoy uses Geocoder for geocoding. We recommend configuring local geocoding or load balancer geocoding so IP addresses are not sent to a 3rd party service. If you do use a 3rd party service and adhere to GDPR, be sure to add it to your subprocessor list. If Ahoy is configured to mask IPs, the masked IP is used (this can reduce accuracy but is better for privacy).
To enable geocoding, add this line to your application’s Gemfile:
gem "geocoder"And update config/initializers/ahoy.rb:
Ahoy.geocode = trueGeocoding is performed in a background job so it doesn’t slow down web requests. The default job queue is :ahoy. Change this with:
Ahoy.job_queue = :low_priorityFor privacy and performance, we recommend geocoding locally.
For city-level geocoding, download the GeoLite2 City database.
Add this line to your application’s Gemfile:
gem "maxminddb"And create config/initializers/geocoder.rb with:
Geocoder.configure(
ip_lookup: :geoip2,
geoip2: {
file: "path/to/GeoLite2-City.mmdb"
}
)For country-level geocoding, install the geoip-database package. It’s preinstalled on Heroku. For Ubuntu, use:
sudo apt-get install geoip-databaseAdd this line to your application’s Gemfile:
gem "geoip"And create config/initializers/geocoder.rb with:
Geocoder.configure(
ip_lookup: :maxmind_local,
maxmind_local: {
file: "/usr/share/GeoIP/GeoIP.dat",
package: :country
}
)Some load balancers can add geocoding information to request headers.
Update config/initializers/ahoy.rb with:
Ahoy.geocode = false
class Ahoy::Store < Ahoy::DatabaseStore
def track_visit(data)
data[:country] = request.headers["<country-header>"]
data[:region] = request.headers["<region-header>"]
data[:city] = request.headers["<city-header>"]
super(data)
end
endAhoy provides a number of options to help with GDPR compliance.
Update config/initializers/ahoy.rb with:
class Ahoy::Store < Ahoy::DatabaseStore
def authenticate(data)
# disables automatic linking of visits and users
end
end
Ahoy.mask_ips = true
Ahoy.cookies = :noneThis:
If you use JavaScript tracking, also set:
ahoy.configure({cookies: false});Ahoy can mask IPs with the same approach Google Analytics uses for IP anonymization. This means:
8.8.4.4 becomes 8.8.4.0)2001:4860:4860:0:0:0:0:8844 becomes 2001:4860:4860::)Ahoy.mask_ips = trueIPs are masked before geolocation is performed.
To mask previously collected IPs, use:
Ahoy::Visit.find_each do |visit|
visit.update_column :ip, Ahoy.mask_ip(visit.ip)
endAhoy can switch from cookies to anonymity sets. Instead of cookies, visitors with the same IP mask and user agent are grouped together in an anonymity set.
Ahoy.cookies = :noneNote: If Ahoy was installed before v5, add an index before making this change.
Previously set cookies are automatically deleted. If you use JavaScript tracking, also set:
ahoy.configure({cookies: false});Data should only be retained for as long as it’s needed. Delete older data with:
Ahoy::Visit.where("started_at < ?", 2.years.ago).find_in_batches do |visits|
visit_ids = visits.map(&:id)
Ahoy::Event.where(visit_id: visit_ids).delete_all
Ahoy::Visit.where(id: visit_ids).delete_all
endYou can use Rollup to aggregate important data before you do.
Ahoy::Visit.rollup("Visits",No open issues yet, or sync has not completed.