Last Updated: July 12, 2022
·
1.932K
· cgarvis

Server-side events with Segment.io for free

The problem with Segment.io Analytics.js is that binding to a form submit doesn't mean that the action was success. I've found a nice little work around so that I can fire events off from the server

First add a track_event method to your Application Controller

class ApplicationController < ActionController::Base
  def track_event(*args)
    json_array = args.to_json.stripe
    json_args = json_array.slice(1, json_array.length - 2)

    flash[:events] ||= Array.new
    flash[:events] << json_args
  end
end

Then we a way to display these "flash events" in our template. So create a helper

module LayoutHelper
  def analytics_events
    Array(flash[:events]).map do |event|
      "analytics.track(#{event})"
    end.join("\n")
  end
end

Lastly, add the following to your template:

script == analytics_events

Now server side analytic events are as easy as

track_event('Created account', plan: 'Free')

1 Response
Add your response

Nice post and very helpful, have some code they may help others:

1) I think you meant to use strip instead of stripe in the track_event method.

2) Also, for people unfamiliar with HAML here is the equivalent code in ERB:

<%= javascript_tag do %>
 <%= analytics_events.html_safe %>
<% end %>

3) Here's a little refactor that may help in clarity:

track_event in application_controller.rb

def track_event(event, options = nil)
    json_args = "#{event.to_json},#{options.to_json}"
    flash[:events] ||= []
    flash[:events] << json_args
  end

and
How to call track_event within a controller

track_event('Signed Up', {user_id: @user.id, 
                        category: 'foobar'})
over 1 year ago ·