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.

No comments: