On the chopping Bloc

July 16, 2012 at 8:25pm
Home

Setting up MixPanel in Rails

Mixpanel is simply awesome. It’s simple to set up and has a great interface to track user generated events in real-time. Here’s how I set it up in my Rails app.

Gem or no gem?

As usually is the case, there is at least one Mixpanel gem out there. I opted NOT to use the gem because Mixpanel is constantly releasing new features (such as the People module) and the gem author doesn’t seem to update it frequently enough. Plus, the Mixpanel is pretty simple to set up anyway.

Rails.env?

First step is create TWO projects on Mixpanel: one for the development environment and for to track actual users (production). This is important in order to keep the real users events clean, but also have an environment where you can mess around in development.

Installation

Back on the Rails app, I created a view partial on ‘shared/_mixpanel’, where I inserted the standard JS snippet you can find one the Mixpanel instructions page. If you take look at that code, you will see the last line is where you should insert the project’s token. Instead, I added a variable:

  mixpanel.init(‘<%= MIXPANEL_TOKEN %>’);


Then I wrapped the whole script around an if-statement that only runs if we are in development or production:

<% if Rails.env.staging? || Rails.env.production? %>
  (…script…)
<% end %>


I put the actual tokens on their respective config/environment files (development.rb and production.rb):

  MIXPANEL_TOKEN = “1234somerandomnumber1234”.freeze


Mixpanel should be ready to receive the events. Now all I had to do is include them in a JS asset file. For example:

jQuery ->
  mixpanel.track_links(‘li #happy_button’, ‘Happy button clicked’)


After clicking the button a few times, the events show up on the Mixpanel dashboard almost instantly.

Most of these suggestions were taken from this Thoughtbot post, so you might want to check it out as well.

Notes

  1. choppingbloc posted this