We will use Rails to initialize the project demo-rails-ahoy:
# Create a new rails project
$ rails new demo-rails-ahoy
$ cd demo-rails-ahoy
# Install gem
$ bundler add ahoy_matey
# Generate install
$ bin/rails g ahoy:install
$ bin/rails db:migrate
# Generate a controller for testing our analytics
$ bin/rails g controller home show
In the above, we add Ahoy with the gem ahoy_matey, use the Ahoy generate for the installation process and then migrate the database for the changes made.
Finally, we create a Home controller for use to setup a basic "show" route localhost:3000/home/{id} that we can create some basic analytics against.
In our example today, we will just be showing how to track an event with the track method.
Updating our routes
Update config/routes.rb for the following:
Rails.application.routes.draw do
resources :home, only: [:show]
end
This will enable the endpoint /home/{id} that we are aiming for.
Next is to set it up in the home controller.
Updating our controller
We will be making a very contrived example for our controller.
Update the app/controllers/home_controller.rb file to the following:
class HomeController < ApplicationController
def show
ahoy.track 'home#show', search_id: params[:id]
render json: { message: 'ok' }
end
end
At this point, our application is actually prepped to record our events.
To debug and test with cURL
We will do some testing using cURL, so the last thing we need to do is update our configuration just for that.
Update the config/initializers/ahoy.rb file to disable Ahoy.quiet and enable Ahoy.track_bots:
class Ahoy::Store < Ahoy::DatabaseStore
end
# set to true for JavaScript tracking
Ahoy.api = false
Ahoy.quiet = false
Ahoy.track_bots = true
# set to true for geocoding (and add the geocoder gem to your Gemfile)
# we recommend configuring local geocoding as well
# see https://github.com/ankane/ahoy#geocoding
Ahoy.geocode = false
Setting those two values will override the defaults.
Ahoy.quiet enables debugging information to be logged to the console.
Ahoy.track_bots will not skip any events from our cURL requests, enabling us to fire up the Rails console and see what is happening when an event is tracked.
Running our code
In one terminal window, run the Rails server bin/rails s.
In another, let's run some cURL commands with different routes: