Verification stats

One of the initial user stories that we defined was:

As a course administrator,
In order to know how often my verification system is being used
I want to track every call to a verification url

That is the feature we will be working on right now.

Before we start developing this feature I would like to take a moment and talk about one of the principles that guide me in my work - to write new code only if I have to. Every new line of code I write is code that needs to be tested, potentially debugged, understood and definitely supported. It's painful for most software developers to acknowledge this, because we love code so much, but the best code is no code at all!

So if we don't need to write any code but still implement a feature and solve a problem - then that must be a good thing, right?

That is exactly what we're going to do with this particular feature.

My idea is that we can use the link shortening service bit.ly that, apart from shortening url's, also provides simple analytics.

We are going to use a ruby wrapper around the BitLy API - found at github.com/philnash/bitly.

This way, we will not have write our own tracking module AND we get to display a shorter validation link on the certificate.

We start with adding the gem to our Gemfile:

# Gemfile

gem 'bitly'

As always, run bundle install to install the new dependency.

In your .env file, add two environmental variables:

# .env

...
BITLY_USERNAME = < bit.ly username >
BITLY_API_KEY= < bit.ly api key >

You'll get those credentials if you sign up for Bit.ly, go to your profile settings (Advanced) and look under the Legacy API Key section.

If you have deployed your application to Heroku, you need to save your credentials as vars on your application as well:

Add the following code to your certificate_generator.rb:

Displaying stats

We need to retrieve stats from bit.ly in two steps.

  1. Identify the resource using the lookup method

  2. Get the statistics by using the global_clicks method

First we need the Certificate to respond to a new method that will give us the verification url. In your certificate_spcec.rb add the following test:

And implement the methods:

At this point we have access to an Certificate instance method #stats that will return the total amount of clicks for us. We can use that on our view:

With this changes we are getting the click count on the valid certificate show page (valid.erb).

We have successfully set up a link shortening service, displayed the link on the generated certificate and we are accessing the analytic functionality of Bit.ly.

Not bad for an hours work, right?

Last updated