Module: AnalyticsInstrumentation

Includes:
AnalyticsAttribution
Included in:
ApplicationController
Defined in:
lib/analytics_instrumentation.rb,
lib/analytics_instrumentation/config.rb,
lib/analytics_instrumentation/version.rb

Defined Under Namespace

Classes: Config

Constant Summary collapse

VERSION =
"0.1.1"

Class Method Summary collapse

Instance Method Summary collapse

Methods included from AnalyticsAttribution

#add_attribution

Class Method Details

.configure {|@@config| ... } ⇒ Object

Yields:

  • (@@config)


25
26
27
28
29
30
31
32
33
# File 'lib/analytics_instrumentation.rb', line 25

def configure(&proc)
  @@config ||= AnalyticsInstrumentation::Config.new
  yield @@config

  # unless @config.valid?
  #   errors = @config.errors.full_messages.join(', ')
  #   raise AnalyticsInstrumentation::Config::Invalid.new(errors)
  # end
end

.included(base) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
# File 'lib/analytics_instrumentation.rb', line 13

def included(base)
  @@segment = Segment::Analytics.new({
      write_key:  @@config.segment_write_key,
      on_error:   @@config.error_handler
  })

  base.class_eval do
    base.send(:after_filter, :analyticsLogPageView)
    base.send(:after_filter, :analyticsCheckSessionStart)
  end
end

Instance Method Details

#analyticsAliasUser(user_id) ⇒ Object



100
101
102
103
104
105
106
107
108
109
110
111
# File 'lib/analytics_instrumentation.rb', line 100

def analyticsAliasUser(user_id)
  return if skip_analytics?

  aliasProperties = {
    previous_id: session[:analytics_id],
    user_id: user_id
  }

  logger.debug "Analytics.alias #{aliasProperties}"
  @@segment.alias(aliasProperties)
  @@segment.flush
end

#analyticsApplyOriginatingPage(properties) ⇒ Object



95
96
97
98
# File 'lib/analytics_instrumentation.rb', line 95

def analyticsApplyOriginatingPage(properties)
  properties["Originating Page Identifier"] = session["previous-page-identifier"]
  properties["Originating Page Type"]       = session["previous-page-type"]
end

#analyticsCheckSessionStartObject



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/analytics_instrumentation.rb', line 36

def analyticsCheckSessionStart
  begin
    return if skip_analytics?
    if current_user
      if !session[:last_seen] || session[:last_seen] < 30.minutes.ago
        analyticsTrackEvent("Session Start")
        if @@config.intercom? && Rails.env.production?
          Intercom.post("https://api.intercom.io/users", {user_id:current_user.id, new_session:true})
        end
      end
      session[:last_seen] = Time.now
    else
      if session[:last_seen_logged_out].nil? || session[:last_seen_logged_out] < 30.minutes.ago
        analyticsTrackEvent("Session Start")
      end
      session[:last_seen_logged_out] = Time.now
    end
  rescue => e
    puts "FOUND ERROR #{e.inspect}"
    puts caller
    puts @@config.inspect
    puts @@config.error_handler.inspect
    @@config.error_handler(e, "Analytics Check Session Crash: #{request.filtered_path}")
  end
end

#analyticsIDObject



177
178
179
180
# File 'lib/analytics_instrumentation.rb', line 177

def analyticsID
  if current_user then return current_user.id end
  raw_analytics_id
end

#analyticsLogPageViewObject



62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/analytics_instrumentation.rb', line 62

def analyticsLogPageView
  begin
    return if skip_analytics?
    return if self.status >= 400

    page_view_event = AnalyticsMapping.to_event(params, self.view_assigns)

    if page_view_event
      if current_user
        analyticsSetPerson(current_user)
      end
      add_attribution page_view_event[:parameters]
      analyticsTrackEvent page_view_event[:name], page_view_event[:parameters]
      analyticsStoreOriginatingPage page_view_event
    end

    properties = {
      page: request.path
    }
    properties.merge! analyticsSuperProperties
    analyticsTrackEvent "Page View", properties
  rescue => e
    @@config.error_handler(e, "Analytics Crash: #{request.filtered_path}")
  end
end

#analyticsSetPerson(user) ⇒ Object



113
114
115
116
117
118
119
120
121
122
123
# File 'lib/analytics_instrumentation.rb', line 113

def analyticsSetPerson(user)
  return if skip_analytics?

  properties = {
    user_id: user.id,
    traits: @@config.custom_user_traits(user)
  }

  logger.debug "Analytics.identify #{JSON.pretty_generate(properties)}"
  @@segment.identify(properties)
end

#analyticsStoreOriginatingPage(page_view_event) ⇒ Object



88
89
90
91
92
93
# File 'lib/analytics_instrumentation.rb', line 88

def analyticsStoreOriginatingPage(page_view_event)
  if !request.xhr?
    session["previous-page-type"]       = page_view_event[:name]
    session["previous-page-identifier"] = page_view_event[:page_identifier]
  end
end

#analyticsSuperPropertiesObject



125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
# File 'lib/analytics_instrumentation.rb', line 125

def analyticsSuperProperties
  superProperties = {
    "Raw Analytics ID" => raw_analytics_id,
    "Ajax" => !request.xhr?.nil?
  }
  if current_user
    superProperties.merge!({
      "User Created At" => current_user.created_at,
      "Username" => current_user.try(:username),
      "Full name" => current_user.try(:full_name),
      "User ID" => current_user.id,
      "Login Provider" => current_user.try(:provider) || "Email"
    })
  end
  superProperties
end

#analyticsTrackEvent(name, properties = {}) ⇒ Object



142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
# File 'lib/analytics_instrumentation.rb', line 142

def analyticsTrackEvent(name, properties={})
  return if skip_analytics?

  properties ||= {}

  properties["logged_in"] = !!current_user
  properties["source"]    = params[:source] if params[:source]

  properties.merge! analyticsSuperProperties
  properties.merge! @@config.extra_event_properties

  analyticsApplyOriginatingPage properties

  analyticsProperties = {
    user_id: analyticsID,
    event: name,
    properties: properties,
    context: {
      userAgent: request.env['HTTP_USER_AGENT'],
      ip: request.remote_ip,
      'Google Analytics' => {
        clientId: googleAnalyticsID
      }
    }
  }

  logger.debug "Analytics.track #{JSON.pretty_generate(analyticsProperties)}"
  @@segment.track(analyticsProperties)
end

#raw_analytics_idObject



172
173
174
175
# File 'lib/analytics_instrumentation.rb', line 172

def raw_analytics_id
  session[:analytics_id] ||= (rand * 1000000000000000).to_i
  session[:analytics_id]
end