Skip to content

Instantly share code, notes, and snippets.

@joshdover
Last active December 25, 2015 03:49
Show Gist options
  • Save joshdover/6912847 to your computer and use it in GitHub Desktop.
Save joshdover/6912847 to your computer and use it in GitHub Desktop.
Rails helper for automatically generating mixpanel tracking for links.
<!-- Include Mixpanel and init before this. -->
<!-- Place at the bottom of your layout (ex: app/views/layouts/application.html.erb) -->
<% if content_for :mixpanel %>
<%= javascript_tag(yield :mixpanel) %>
<% end %>
# app/helpers/mixpanel_helper.rb
module MixpanelHelper
# This should only be used with server-side data, no user input.
def track_links(selector, name, properties)
if properties.nil?
js = "mixpanel.track_links('#{selector}', '#{name}');"
else
js = "mixpanel.track_links('#{selector}', '#{name}', #{properties.to_json});"
end
content_for :mixpanel do
js.html_safe
end
end
end
module ActionView::Helpers::UrlHelper
include MixpanelHelper
# Used to generate unique IDs for tracked links. These are reset with each request.
def next_uid
@rand_hex = SecureRandom.hex(4) if @rand_hex.nil?
@unique_count = 0 if @unique_count.nil?
@unique_count += 1
"mp-#{@rand_hex}-#{@unique_count}"
end
# Aliased so that we can still call ActionView's link_to helper.
alias_method :old_link_to, :link_to unless method_defined? :old_link_to
# Overrides the default `link_to` helper to allow generation of Mixpanel tracking JS.
# You are not required to provide an ID. Usage:
#
# link_to "My link", my_path, event: {name: "required", selector: ".optional",
# properties: {optional: true, "this is awesome" => "duh"}}
def link_to(*args, &block)
if block_given?
name = capture(&block)
options = args[0] || {}
html_options = args[1] || {}
else
name = args[0]
options = args[1] || {}
html_options = args[2] || {}
end
event = html_options.delete(:event) || {}
if event[:selector].nil? && html_options[:id].nil? && !event[:name].nil?
html_options[:id] = next_uid
end
link_tag = old_link_to(name, options, html_options)
unless event[:name].nil?
track_links("#{event[:selector] || '#' + html_options[:id]}", event[:name], event[:properties])
end
link_tag
end
end
<!-- Below is what will be generated by the new link_to helper. -->
<a href="/my_path" id="mp-07c6f089-2">My link</a>
<script type="text/javascript">
mixpanel.track_links("#mp-07c6f089-2", "clicked my link", {resource_id: 2});
</script>
<!-- Place this in any view to track the link to automatically generate the appropriate JS.
'properties' hash will be passed to mixpanel as a JSON object -->
<%= link_to "My link", my_path, event: {name: "clicked my link",
properties: {resource_id: resource.id}} %>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment