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

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



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

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



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

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



188
189
190
191
# File 'lib/analytics_instrumentation.rb', line 188

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
# 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
      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



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

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



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

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



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

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



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

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
      }
    },
    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



183
184
185
186
# File 'lib/analytics_instrumentation.rb', line 183

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