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.
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:
$ heroku config:set BITLY_USERNAME=< bit.ly username >
$ heroku config:set BITLY_API_KEY=< bit.ly api key >
# On your deployed app add:
$ heroku config:set SERVER_URL=< your heroku url WITH an extra '/verify/' at the end <- Important! >
Add the following code to your certificate_generator.rb:
We need to retrieve stats from bit.ly in two steps.
Identify the resource using the lookup method
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:
# specs/certificate_spec.rb...# in the main describe block:it 'returns #bitly_lookup'doexpect(@certificate.bitly_lookup).to eq "http://localhost:9292/verify/#{@certificate.identifier}"endit 'returns #stats'doexpect(@certificate.stats).to eq 0end
And implement the methods:
# lib/certificate.rbrequire'bitly'...defstatsBitly.use_api_version_3 bitly = Bitly.new(ENV['BITLY_USERNAME'],ENV['BITLY_API_KEY'])begin bitly.lookup(self.bitly_lookup).global_clicksrescue0endenddefbitly_lookup server = ENV['SERVER_URL'] ||'http://localhost:9292/verify/'"#{server}#{self.identifier}"end...
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.