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.5"

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



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

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



93
94
95
96
# File 'lib/analytics_instrumentation.rb', line 93

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
# 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
    logger.debug "Errpr found in analyticsCheckSessionStart: #{e.inspect}"
    @@config.error_handler.call(e, "Analytics Check Session Crash: #{request.filtered_path}")
  end
end

#analyticsIDObject



180
181
182
183
# File 'lib/analytics_instrumentation.rb', line 180

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

#analyticsLogPageViewObject



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

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
    logger.debug "Errpr found in analyticsLogPageView: #{e.inspect}"
    @@config.error_handler.call(e, "Analytics Crash: #{request.filtered_path}")
  end
end

#analyticsSetPerson(user) ⇒ Object



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

def analyticsSetPerson(user)
  return if skip_analytics?

  user_traits = instance_exec(user, &@@config.custom_user_traits)

  properties = {
    user_id: user.id,
    traits: (user_traits||{})
  }

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

#analyticsStoreOriginatingPage(page_view_event) ⇒ Object



86
87
88
89
90
91
# File 'lib/analytics_instrumentation.rb', line 86

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
171
172
173
# 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

  # User defined extra props, called in context
  extra_props = instance_exec(&@@config.extra_event_properties)
  properties.merge! (extra_props || {})

  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



175
176
177
178
# File 'lib/analytics_instrumentation.rb', line 175

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