Skip to content

Instantly share code, notes, and snippets.

@jrallison
Created October 5, 2011 15:40
Show Gist options
  • Save jrallison/1264762 to your computer and use it in GitHub Desktop.
Save jrallison/1264762 to your computer and use it in GitHub Desktop.
Mixpanel server events
# In controllers
mixpanel("event name")
# Anywhere else
Mixpanel.new(:event => "event name", :id => some_user.id, :ip => ???).track!
# ApplicationController
def mixpanel(event, opts = {})
unless current_user.admin? || masquerading?
opts = {:event => event, :id => current_user.id, :ip => request.remote_ip}.merge(opts)
Mixpanel.new(opts).track!
end
end
# lib/mixpanel.rb
class Mixpanel
TOKEN = SOME_MIXPANEL_TOKEN
attr_accessor :options
attr_accessor :event
def initialize(opts = {})
@options = {}
@options['ip'] = opts[:ip] unless opts[:ip].nil?
@options['time'] = Time.now.to_i
@options['token'] = TOKEN
@options['distinct_id'] = opts[:id] unless opts[:id].blank?
@event = opts[:event] unless opts[:event].nil?
opts.each do |key, value|
unless [:ip, :id, :event, :step].include? key
@options[key.to_s] = value.to_s
end
if [:step].include? key
@options[key.to_s] = value.to_i
end
end
end
def raw_data
hash = {}
hash['event'] = @event
hash['properties'] = @options
ActiveSupport::JSON.encode(hash)
end
def serialize_data
Base64.encode64s(raw_data)
end
def url
ret = "http://api.mixpanel.com/track/?data=#{serialize_data}"
ret += "&ip=1" unless @options['ip']
ret
end
def track!
Rails.logger.info "Mixpanel: #{@event}, #{self.url}"
params = { :data => serialize_data }
params[:ip] = 1 unless @options['ip']
Resque.enqueue(MixpanelJob, params) if Rails.env.production?
end
end
# lib/jobs/mixpanel_job.rb
require 'net/http'
class MixpanelJob
def self.perform(params)
res = Net::HTTP.start("api.mixpanel.com", 80) {|http|
http.read_timeout = 3
http.request_post("/track/", params.to_query)
}
end
def self.queue
:mixpanel
end
end
@jrallison
Copy link
Author

jrallison commented Oct 5, 2011 via email

@jrallison
Copy link
Author

jrallison commented Oct 5, 2011 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment