Skip to content

Instantly share code, notes, and snippets.

@bricker
Created September 24, 2012 07:31
Show Gist options
  • Save bricker/3774768 to your computer and use it in GitHub Desktop.
Save bricker/3774768 to your computer and use it in GitHub Desktop.
tracking_link_to
# Wrapper around link_to to help with event tracking links.
# Adds the `track-event` class (even if another class is present)
# and adds the tracking data to the data attributes hash.
#
# Usage:
#
# tracking_link_to "Events", event_path, category: "Events", action: "Visit Events", label: "Events"
#
# If you need to pass html_options, be sure to let it know where one hash ends and the other begins:
#
# tracking_link_to "News", news_path, { category: "News", action: "Clicked News", label: "News" },
# class: "extra-class", data: { extra: "Extra Stuff" }
#
def tracking_link_to(*args)
tracking_options = args[2] || {}
html_options = args[3] || {}
# Merge in `track-event` class for all tracking links
html_options[:class] = [html_options[:class], "track-event"].compact.join " "
# Turn tracking options into data attributes
html_options[:data] ||= {}
html_options[:data].merge!(
ga_category: tracking_options[:category],
ga_action: tracking_options[:action],
ga_label: tracking_options[:label]
)
# Pass it off to link_to
link_to args[0], args[1], html_options
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment