How ankane/ahoy works
Project Type and Purpose
• Ahoy is a Ruby gem / Rails Engine providing first-party analytics for Rails applications.
• It exposes HTTP API endpoints (/ahoy/visits, /ahoy/events) and ships with a default database store, while allowing custom stores (Kafka, Kinesis, etc.).
• It integrates client-side libraries (ahoy.js, native SDKs) with server-side tracking logic, background jobs (geocoding), and ActiveRecord/Mongoid models.
Main Architectural Components
A. Clients
– Web browser running ahoy.js
– Native mobile apps (iOS, Android)
– AMP pages
B. Host Rails Application
– Mounts the Ahoy Rails Engine
– Your existing controllers, views, and models (e.g., Order, User)
– Authentication framework (Devise, Doorkeeper, or custom)
C. Ahoy Engine (in app/controllers/ahoy, lib/ahoy/engine.rb)
– Controllers: VisitsController, EventsController
– Routes: mounted under /ahoy via config/routes.rb in the engine
– Tracker (lib/ahoy/tracker.rb) invoked by controllers and by your app via ahoy.track
– Models: Ahoy::Visit, Ahoy::Event (ActiveRecord/Mongoid) and query methods (lib/ahoy/query_methods.rb)
– Generators (lib/generators/ahoy) for migrations, models, and initializer templates
D. Data Store Layer
– Default: Ahoy::DatabaseStore writes visits & events to your Rails DB
– Custom: any subclass of Ahoy::BaseStore (Kafka, RabbitMQ, Fluentd, etc.)
– Store methods: track_visit, track_event, geocode, authenticate
E. Background Job Processor
– Geocoding job (lib/ahoy/geocode_v2_job.rb) enqueued on :ahoy queue
– Any other asynchronous tasks (e.g., custom data-store flush)
F. External Services
– Geocoding services (third-party API or local MaxMind DB)
– Third-party analytics sinks (Kafka, Kinesis, NSQ, etc.)
– Exception reporters (Rollbar via Safely)
Relationships & Data Flow
1. Client → HTTP(S) POST to /ahoy/visits → Ahoy::VisitsController#create
2. Controller calls Ahoy::Tracker#track_visit → delegates to your Ahoy::Store → writes to DB or pushes to message queue
3. Visit model persisted; background job enqueues geocoding: Ahoy::GeocodeV2Job.perform_later(visit_id)
4. Client or server calls ahoy.track → HTTP POST to /ahoy/events → Ahoy::EventsController#create → track_event in store
5. Authentication hook (Ahoy::Store#authenticate) links current_user to ahoy_visit_id
6. Host App models use visitable to join visits, enabling queries like Order.joins(:ahoy_visit)
7. Query layer (QueryMethods) handles JSON, HSTORE, arrays across MySQL, Postgres, SQLite, MongoDB
Architectural Patterns & Design Principles
– Plugin architecture: shipped as a self-contained Rails Engine
– Store subscriber pattern: base store with hook methods, easily extendable
– MVC (controllers → tracker → store → models)
– Asynchronous background processing for geocoding and heavy tasks
– Separation of concerns: tracking logic lives in the engine, your app handles domain models