Tuesday, September 16, 2008

Google Analytics Campaign URL Encoding with Ruby on Rails

So we're launching a couple pages that we wanted to enrich the links and encode them with the Google Analytics campaign tracking data. (If you're not familiar with it, you can take a look at the url builder here).

Basically, you create a campaign source (email, ad, or whatever) a medium and a name and it will build a url for you.

All of the links on the page we were building had the same source and campaign name, but different medium names.

So at the top of the page in the view (I thought about doing this in the controller, but for our purposes it is a per page kind of thing) I added a little erb code:
<% source_link = 'blah' medium_link1 = 'link1' medium_link2 = 'link2' campaign_link = 'nameofcampaign' %>



Now, when you have a link_to helper in your page, add the following parameters after the :action


:utm_source => source_link, :utm_medium => medium_link1, :utm_campaign => campaign_link

This way, if you want to update the URL encoding for Google Analytics for a different campaign down the line, it's a matter of just changing the variables at the top of the page, rather than going down through the whole view to change every source and every campaign link.

Anyways, I felt proud of myself to be a little bit more DRY in my view with Google Analytics Campaign URL encoding.

Using before_save in the model

I was doing some refactoring of our email subscription functionality and I added a table column to include a hash of the email address which I would use in the unsubscribe process.

So I created a new migration that added the column and calculated the hashes for the existing email addresses in the table, however, it was not automatically creating the hashes using the current functionality.

So, it's a pretty simple call in the model, a function called before_save.

My model file ends up looking like this, which creates the hash right before it saves the email address when someone subscribes.
before_save :add_email_hash

def add_email_hash
self.email_hash = Digest::SHA1.hexdigest(self.email + "addsometexttomakeithardtorecreate")
end

And that's it! An addition to the model file which is supposed to handle this sort of thing, rather than the controller.