Module: AnalyticsInstrumentation

Includes:
AnalyticsAttribution
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.2.3"

Class Method Summary collapse

Instance Method Summary collapse

Methods included from AnalyticsAttribution

#add_attribution

Class Method Details

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

Yields:

  • (@@config)


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

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



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

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



103
104
105
106
107
108
109
110
111
112
113
114
# File 'lib/analytics_instrumentation.rb', line 103

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



98
99
100
101
# File 'lib/analytics_instrumentation.rb', line 98

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

#analyticsCheckSessionStartObject



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

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?
          begin
            Intercom.post("https://api.intercom.io/users", {user_id:current_user.id, new_session:true})
          rescue
          end
        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



190
191
192
193
# File 'lib/analytics_instrumentation.rb', line 190

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

#analyticsLogPageViewObject



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

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
      analyticsTrackEvent page_view_event[:name], page_view_event[:parameters]
      analyticsStoreOriginatingPage page_view_event
    end

    properties = {
      page: request.path
    }

    track_page_view = request.xhr? ? @@config.track_ajax_as_page_view : true

    analyticsTrackEvent("Page View", properties) if track_page_view
  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



116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
# File 'lib/analytics_instrumentation.rb', line 116

def analyticsSetPerson(user)
  return if skip_analytics?

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

  properties = {
    user_id: user.id,
    traits: (user_traits||{}),
    integrations: {
      # Don't send leads to C.io if they don't have an email
      "Customer.io" => (!user.email.blank?)
    }
  }

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

#analyticsStoreOriginatingPage(page_view_event) ⇒ Object



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

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



134
135
136
137
138
139
140
141
142
143
144
145
# File 'lib/analytics_instrumentation.rb', line 134

def analyticsSuperProperties
  superProperties = {
    "Raw Analytics ID" => raw_analytics_id,
    "Ajax" => !request.xhr?.nil?,
    "Platform" => analyticsPlatform
  }
  if current_user
    user_traits = instance_exec(current_user, &@@config.custom_user_traits)
    superProperties.merge!({user:user_traits}) if user_traits
  end
  superProperties
end

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



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
174
175
176
177
178
179
180
181
182
183
# File 'lib/analytics_instrumentation.rb', line 147

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

  properties ||= {}

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

  properties.merge! analyticsSuperProperties
  add_attribution properties

  # 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
      }
    },
    integrations: {
      # Don't send leads to C.io if they don't have an email
      "Customer.io" => !!current_user
    }
  }

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

#raw_analytics_idObject



185
186
187
188
# File 'lib/analytics_instrumentation.rb', line 185

def raw_analytics_id
  session[:analytics_id] ||= SecureRandom.uuid
  session[:analytics_id]
end