• Stars
    star
    1,051
  • Rank 43,859 (Top 0.9 %)
  • Language
    Ruby
  • License
    MIT License
  • Created over 10 years ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

First-party email analytics for Rails

Ahoy Email

First-party email analytics for Rails

๐Ÿ”ฅ For web and native app analytics, check out Ahoy

๐Ÿš„ To manage email subscriptions, check out Mailkick

Build Status

Installation

Add this line to your applicationโ€™s Gemfile:

gem "ahoy_email"

Getting Started

There are three main features, which can be used independently:

Message History

To encrypt email addresses with Lockbox, install Lockbox and Blind Index and run:

rails generate ahoy:messages --encryption=lockbox
rails db:migrate

To use Active Record encryption (Rails 7+, experimental), run:

rails generate ahoy:messages --encryption=activerecord
rails db:migrate

If you prefer not to encrypt data, run:

rails generate ahoy:messages --encryption=none
rails db:migrate

Then, add to mailers:

class CouponMailer < ApplicationMailer
  has_history
end

Use the Ahoy::Message model to query messages:

Ahoy::Message.last

Use only and except to limit actions

class CouponMailer < ApplicationMailer
  has_history only: [:welcome]
end

To store history for all mailers, create config/initializers/ahoy_email.rb with:

AhoyEmail.default_options[:message] = true

Users

By default, Ahoy Email tries @user then params[:user] then User.find_by(email: message.to) to find the user. You can pass a specific user with:

class CouponMailer < ApplicationMailer
  has_history user: -> { params[:some_user] }
end

The user association is polymorphic, so use it with any model.

To get all messages sent to a user, add an association:

class User < ApplicationRecord
  has_many :messages, class_name: "Ahoy::Message", as: :user
end

And run:

user.messages

Extra Data

Add extra data to messages. Create a migration like:

class AddCouponIdToAhoyMessages < ActiveRecord::Migration[7.1]
  def change
    add_column :ahoy_messages, :coupon_id, :integer
  end
end

And use:

class CouponMailer < ApplicationMailer
  has_history extra: {coupon_id: 1}
end

You can use a proc as well.

class CouponMailer < ApplicationMailer
  has_history extra: -> { {coupon_id: params[:coupon].id} }
end

Options

Set global options

AhoyEmail.default_options[:user] = -> { params[:admin] }

Use a different model

AhoyEmail.message_model = -> { UserMessage }

Or fully customize how messages are tracked

AhoyEmail.track_method = lambda do |data|
  # your code
end

Data Retention

Delete older data with:

Ahoy::Message.where("created_at < ?", 1.year.ago).in_batches.delete_all

Delete data for a specific user with:

Ahoy::Message.where(user_id: 1, user_type: "User").in_batches.delete_all

UTM Tagging

Use UTM tagging to attribute visits or conversions to an email campaign. Add UTM parameters to links with:

class CouponMailer < ApplicationMailer
  utm_params
end

The defaults are:

  • utm_medium - email
  • utm_source - the mailer name like coupon_mailer
  • utm_campaign - the mailer action like offer

You can customize them with:

class CouponMailer < ApplicationMailer
  utm_params utm_campaign: -> { "coupon#{params[:coupon].id}" }
end

Use only and except to limit actions

class CouponMailer < ApplicationMailer
  utm_params only: [:welcome]
end

Skip specific links with:

<%= link_to "Go", some_url, data: {skip_utm_params: true} %>

Click Analytics

You can track click-through rate to see how well campaigns are performing. Stats can be stored in your database, Redis, or any other data store.

Database

Run:

rails generate ahoy:clicks
rails db:migrate

And create config/initializers/ahoy_email.rb with:

AhoyEmail.subscribers << AhoyEmail::DatabaseSubscriber
AhoyEmail.api = true

Redis

Add this line to your applicationโ€™s Gemfile:

gem "redis"

And create config/initializers/ahoy_email.rb with:

# pass your Redis client if you already have one
AhoyEmail.subscribers << AhoyEmail::RedisSubscriber.new(redis: Redis.new)
AhoyEmail.api = true

Other

Create config/initializers/ahoy_email.rb with:

class EmailSubscriber
  def track_send(data)
    # your code
  end

  def track_click(data)
    # your code
  end

  def stats(campaign)
    # optional, for AhoyEmail.stats
  end
end

AhoyEmail.subscribers << EmailSubscriber
AhoyEmail.api = true

Usage

Add to mailers you want to track

class CouponMailer < ApplicationMailer
  track_clicks campaign: "my-campaign"
end

If storing stats in the database, the mailer should also use has_history

Use only and except to limit actions

class CouponMailer < ApplicationMailer
  track_clicks campaign: "my-campaign", only: [:welcome]
end

Or make it conditional

class CouponMailer < ApplicationMailer
  track_clicks campaign: "my-campaign", if: -> { params[:user].opted_in? }
end

You can also use a proc

class CouponMailer < ApplicationMailer
  track_clicks campaign: -> { "coupon-#{action_name}" }
end

Skip specific links with:

<%= link_to "Go", some_url, data: {skip_click: true} %>

By default, unsubscribe links are excluded. To change this, use:

AhoyEmail.default_options[:unsubscribe_links] = true

You can specify the domain to use with:

AhoyEmail.default_options[:url_options] = {host: "mydomain.com"}

Stats

Get stats for a campaign

AhoyEmail.stats("my-campaign")

Upgrading

2.0

Ahoy Email 2.0 brings a number of changes. Here are a few to be aware of:

  • The to field is encrypted by default for new installations. If youโ€™d like to encrypt an existing installation, install Lockbox and Blind Index and follow the Lockbox instructions for migrating existing data.

    For the model, create app/models/ahoy/message.rb with:

    class Ahoy::Message < ActiveRecord::Base
      self.table_name = "ahoy_messages"
    
      belongs_to :user, polymorphic: true, optional: true
    
      encrypts :to, migrating: true
      blind_index :to, migrating: true
    end
  • The track method has been broken into:

    • has_history for message history
    • utm_params for UTM tagging
    • track_clicks for click analytics
  • Message history is no longer enabled by default. Add has_history to individual mailers, or create an initializer with:

    AhoyEmail.default_options[:message] = true
  • For privacy, open tracking has been removed.

  • For clicks, we encourage you to try aggregate analytics to measure the performance of campaigns. You can use a library like Rollup to aggregate existing data, then drop the token and clicked_at columns.

    To keep individual analytics, use has_history and track_clicks campaign: false and create an initializer with:

    AhoyEmail.save_token = true
    AhoyEmail.subscribers << AhoyEmail::MessageSubscriber

    If you use a custom subscriber, :message is no longer included in click events. You can use :token to query the message if needed.

  • Users are shown a link expired page when signature verification fails instead of being redirected to the homepage when AhoyEmail.invalid_redirect_url is not set

History

View the changelog

Contributing

Everyone is encouraged to help improve this project. Here are a few ways you can help:

To get started with development:

git clone https://github.com/ankane/ahoy_email.git
cd ahoy_email
bundle install
bundle exec rake test

More Repositories

1

pghero

A performance dashboard for Postgres
Ruby
7,123
star
2

searchkick

Intelligent search made easy
Ruby
6,257
star
3

chartkick

Create beautiful JavaScript charts with one line of Ruby
Ruby
6,157
star
4

blazer

Business intelligence made simple
Ruby
4,511
star
5

ahoy

Simple, powerful, first-party analytics for Rails
Ruby
3,872
star
6

strong_migrations

Catch unsafe migrations in development
Ruby
3,662
star
7

groupdate

The simplest way to group temporal data
Ruby
3,617
star
8

pgsync

Sync data from one Postgres database to another
Ruby
2,787
star
9

the-ultimate-guide-to-ruby-timeouts

Timeouts for popular Ruby gems
Ruby
2,212
star
10

production_rails

Best practices for running Rails in production
1,975
star
11

dexter

The automatic indexer for Postgres
Ruby
1,491
star
12

lockbox

Modern encryption for Ruby and Rails
Ruby
1,290
star
13

chartkick.js

Create beautiful charts with one line of JavaScript
JavaScript
1,211
star
14

react-chartkick

Create beautiful JavaScript charts with one line of React
JavaScript
1,183
star
15

pretender

Log in as another user in Rails
Ruby
1,124
star
16

secure_rails

Rails security best practices
954
star
17

pgslice

Postgres partitioning as easy as pie
Ruby
953
star
18

mailkick

Email subscriptions for Rails
Ruby
847
star
19

vue-chartkick

Create beautiful JavaScript charts with one line of Vue
JavaScript
747
star
20

eps

Machine learning for Ruby
Ruby
609
star
21

awesome-legal

Awesome free legal documents for companies
589
star
22

searchjoy

Search analytics made easy
Ruby
579
star
23

polars-ruby

Blazingly fast DataFrames for Ruby
Ruby
563
star
24

torch.rb

Deep learning for Ruby, powered by LibTorch
Ruby
552
star
25

blind_index

Securely search encrypted database fields
Ruby
470
star
26

safely

Rescue and report exceptions in non-critical code
Ruby
470
star
27

authtrail

Track Devise login activity
Ruby
466
star
28

multiverse

Multiple databases for Rails ๐ŸŽ‰
Ruby
463
star
29

ahoy.js

Simple, powerful JavaScript analytics
JavaScript
463
star
30

hightop

A nice shortcut for group count queries
Ruby
462
star
31

field_test

A/B testing for Rails
Ruby
460
star
32

s3tk

A security toolkit for Amazon S3
Python
439
star
33

disco

Recommendations for Ruby and Rails using collaborative filtering
Ruby
431
star
34

active_median

Median and percentile for Active Record, Mongoid, arrays, and hashes
Ruby
427
star
35

informers

State-of-the-art natural language processing for Ruby
Ruby
417
star
36

notable

Track notable requests and background jobs
Ruby
402
star
37

shorts

Short, random tutorials and posts
379
star
38

tensorflow-ruby

Deep learning for Ruby
Ruby
350
star
39

distribute_reads

Scale database reads to replicas in Rails
Ruby
328
star
40

slowpoke

Rack::Timeout enhancements for Rails
Ruby
327
star
41

prophet-ruby

Time series forecasting for Ruby
Ruby
321
star
42

rover

Simple, powerful data frames for Ruby
Ruby
311
star
43

groupdate.sql

The simplest way to group temporal data
PLpgSQL
280
star
44

kms_encrypted

Simple, secure key management for Lockbox and attr_encrypted
Ruby
235
star
45

jetpack

A friendly package manager for R
R
234
star
46

neighbor

Nearest neighbor search for Rails and Postgres
Ruby
230
star
47

rollup

Rollup time-series data in Rails
Ruby
230
star
48

hypershield

Shield sensitive data in Postgres and MySQL
Ruby
227
star
49

logstop

Keep personal data out of your logs
Ruby
218
star
50

pdscan

Scan your data stores for unencrypted personal data (PII)
Go
213
star
51

delete_in_batches

Fast batch deletes for Active Record and Postgres
Ruby
202
star
52

vega-ruby

Interactive charts for Ruby, powered by Vega and Vega-Lite
Ruby
192
star
53

mapkick

Create beautiful JavaScript maps with one line of Ruby
Ruby
173
star
54

dbx

A fast, easy-to-use database library for R
R
171
star
55

fastText-ruby

Efficient text classification and representation learning for Ruby
Ruby
162
star
56

autosuggest

Autocomplete suggestions based on what your users search
Ruby
162
star
57

swipeout

Swipe-to-delete goodness for the mobile web
JavaScript
159
star
58

pghero.sql

Postgres insights made easy
PLpgSQL
154
star
59

mainstreet

Address verification for Ruby and Rails
Ruby
149
star
60

or-tools-ruby

Operations research tools for Ruby
Ruby
139
star
61

mapkick.js

Create beautiful, interactive maps with one line of JavaScript
JavaScript
138
star
62

trend-ruby

Anomaly detection and forecasting for Ruby
Ruby
128
star
63

mitie-ruby

Named-entity recognition for Ruby
Ruby
122
star
64

barkick

Barcodes made easy
Ruby
120
star
65

ownership

Code ownership for Rails
Ruby
111
star
66

anomaly

Easy-to-use anomaly detection for Ruby
Ruby
98
star
67

errbase

Common exception reporting for a variety of services
Ruby
87
star
68

tokenizers-ruby

Fast state-of-the-art tokenizers for Ruby
Rust
81
star
69

ip_anonymizer

IP address anonymizer for Ruby and Rails
Ruby
79
star
70

str_enum

String enums for Rails
Ruby
75
star
71

faiss-ruby

Efficient similarity search and clustering for Ruby
C++
73
star
72

trend-api

Anomaly detection and forecasting API
R
71
star
73

archer

Rails console history for Heroku, Docker, and more
Ruby
70
star
74

onnxruntime-ruby

Run ONNX models in Ruby
Ruby
70
star
75

xgboost-ruby

High performance gradient boosting for Ruby
Ruby
69
star
76

secure-spreadsheet

Encrypt and password protect sensitive CSV and XLSX files
JavaScript
66
star
77

active_hll

HyperLogLog for Rails and Postgres
Ruby
66
star
78

guess

Statistical gender detection for Ruby
Ruby
60
star
79

morph

An encrypted, in-memory, key-value store
C++
59
star
80

lightgbm-ruby

High performance gradient boosting for Ruby
Ruby
56
star
81

midas-ruby

Edge stream anomaly detection for Ruby
Ruby
54
star
82

moves

Ruby client for Moves
Ruby
54
star
83

blingfire-ruby

High speed text tokenization for Ruby
Ruby
54
star
84

vowpalwabbit-ruby

Fast online machine learning for Ruby
Ruby
52
star
85

xlearn-ruby

High performance factorization machines for Ruby
Ruby
51
star
86

tomoto-ruby

High performance topic modeling for Ruby
C++
51
star
87

trove

Deploy machine learning models in Ruby (and Rails)
Ruby
50
star
88

mapkick-static

Create beautiful static maps with one line of Ruby
Ruby
42
star
89

ahoy_events

Simple, powerful event tracking for Rails
Ruby
42
star
90

practical-search

Letโ€™s make search a better experience for our users
40
star
91

breakout-ruby

Breakout detection for Ruby
Ruby
40
star
92

plu

Price look-up codes made easy
Ruby
40
star
93

ngt-ruby

High-speed approximate nearest neighbors for Ruby
Ruby
39
star
94

gindex

Concurrent index migrations for Rails
Ruby
39
star
95

clockwork_web

A web interface for Clockwork
Ruby
38
star
96

ahoy_guide

A foundation of knowledge and libraries for solid analytics
38
star
97

notable_web

A web interface for Notable
HTML
36
star
98

AnomalyDetection.rb

Time series anomaly detection for Ruby
Ruby
34
star
99

khiva-ruby

High-performance time series algorithms for Ruby
Ruby
34
star
100

immudb-ruby

Ruby client for immudb, the immutable database
Ruby
34
star