Skip to content
This repository has been archived by the owner on Aug 10, 2020. It is now read-only.

Commit

Permalink
Browse files Browse the repository at this point in the history
Merge remote-tracking branch 'upstream/master'
  • Loading branch information
dipth committed Mar 24, 2014
2 parents c4ca568 + fe5b73f commit 5aa2f92
Show file tree
Hide file tree
Showing 16 changed files with 475 additions and 29 deletions.
70 changes: 62 additions & 8 deletions .rvmrc
@@ -1,8 +1,62 @@
export RUBYOPT="rubygems"
export RUBYLIB="."
rvm ruby-1.8.7-p174@analytical

# Install bundler if it doesn't already exist
# if ! command -v bundle > /dev/null ; then
# gem install bundler
# fi
#!/usr/bin/env bash

# This is an RVM Project .rvmrc file, used to automatically load the ruby
# development environment upon cd'ing into the directory

# First we specify our desired <ruby>[@<gemset>], the @gemset name is optional,
# Only full ruby name is supported here, for short names use:
# echo "rvm use 2.0.0" > .rvmrc
environment_id="ruby-2.0.0-p353@analytical"

# Uncomment the following lines if you want to verify rvm version per project
# rvmrc_rvm_version="1.24.7 (master)" # 1.10.1 seems like a safe start
# eval "$(echo ${rvm_version}.${rvmrc_rvm_version} | __rvm_awk -F. '{print "[[ "$1*65536+$2*256+$3" -ge "$4*65536+$5*256+$6" ]]"}' )" || {
# echo "This .rvmrc file requires at least RVM ${rvmrc_rvm_version}, aborting loading."
# return 1
# }

# First we attempt to load the desired environment directly from the environment
# file. This is very fast and efficient compared to running through the entire
# CLI and selector. If you want feedback on which environment was used then
# insert the word 'use' after --create as this triggers verbose mode.
if [[ -d "${rvm_path:-$HOME/.rvm}/environments"
&& -s "${rvm_path:-$HOME/.rvm}/environments/$environment_id" ]]
then
\. "${rvm_path:-$HOME/.rvm}/environments/$environment_id"
for __hook in "${rvm_path:-$HOME/.rvm}/hooks/after_use"*
do
if [[ -f "${__hook}" && -x "${__hook}" && -s "${__hook}" ]]
then \. "${__hook}" || true
fi
done
unset __hook
if (( ${rvm_use_flag:=1} >= 2 )) # display only when forced
then
if [[ $- == *i* ]] # check for interactive shells
then printf "%b" "Using: $(tput setaf 2 2>/dev/null)$GEM_HOME$(tput sgr0 2>/dev/null)
" # show the user the ruby and gemset they are using in green
else printf "%b" "Using: $GEM_HOME
" # don't use colors in non-interactive shells
fi
fi
else
# If the environment file has not yet been created, use the RVM CLI to select.
rvm --create "$environment_id" || {
echo "Failed to create RVM environment '${environment_id}'."
return 1
}
fi

# If you use bundler, this might be useful to you:
# if [[ -s Gemfile ]] && {
# ! builtin command -v bundle >/dev/null ||
# builtin command -v bundle | GREP_OPTIONS="" \grep $rvm_path/bin/bundle >/dev/null
# }
# then
# printf "%b" "The rubygem 'bundler' is not installed. Installing it now.\n"
# gem install bundler
# fi
# if [[ -s Gemfile ]] && builtin command -v bundle >/dev/null
# then
# bundle install | GREP_OPTIONS="" \grep -vE '^Using|Your bundle is complete'
# fi
4 changes: 2 additions & 2 deletions README.rdoc
Expand Up @@ -2,8 +2,6 @@

Gem for managing multiple analytics services in your rails app.

=== NOTE: This gem is looking for a new maintainer, or some help from a committed user. I haven't had enough time in a while to test & merge pull-requests, and I would love some help from anyone who is interested in picking it up.

{<img src="https://secure.travis-ci.org/jkrall/analytical.png" />}[http://travis-ci.org/jkrall/analytical]

Service implementations include:
Expand All @@ -24,6 +22,7 @@ Service implementations include:
* MixPanel[http://www.mixpanel.com]
* Gauges[http://get.gaug.es]
* Segment.io[http://segment.io]
* Mouseflow[http://mouseflow.com]

== Usage

Expand Down Expand Up @@ -175,6 +174,7 @@ These fine folks have contributed patches and new features to this project:
* {Kurt Werle}[http://github.com/kwerle]
* {Olivier Lauzon}[http://github.com/olauzon]
* {Chris Ricca}[https://github.com/ChrisRicca]
* {Rajiv Aaron Manglani}[https://github.com/rajiv]
* {Thomas Dippel}[https://github.com/dipth]

Thanks guys!
Expand Down
2 changes: 1 addition & 1 deletion lib/analytical.rb
Expand Up @@ -49,7 +49,7 @@ def analytical
options[:modules] = []
end
options[:session] = session if options[:use_session_store]
if analytical_is_robot?(request.user_agent)
if analytical_is_robot?(request.user_agent, options[:user_agent_whitelist] || [])
options[:modules] = []
end
options[:modules] = options[:filter_modules].call(self, options[:modules]) if options[:filter_modules]
Expand Down
8 changes: 5 additions & 3 deletions lib/analytical/bot_detector.rb
@@ -1,7 +1,9 @@
module Analytical
module BotDetector

def analytical_is_robot?(user_agent)
def analytical_is_robot?(user_agent, whitelist = [])
whitelist = Array(whitelist)

unless user_agent.blank?
user_agent = user_agent.to_s.downcase

Expand All @@ -11,7 +13,7 @@ def analytical_is_robot?(user_agent)
# information. Finally anything that starts with a word in the $whitelist
# is never considered a bot.

whitelist = %w(w3m dillo links elinks lynx)
whitelist.concat %w(w3m dillo links elinks lynx)
whitelist.each do |word|
return false if user_agent.index(word) == 0
end
Expand Down Expand Up @@ -43,4 +45,4 @@ def analytical_is_robot?(user_agent)
end

end
end
end
2 changes: 1 addition & 1 deletion lib/analytical/modules/adroll.rb
Expand Up @@ -24,7 +24,7 @@ def init_javascript(location)
scr.setAttribute('async', 'true');
scr.type = "text/javascript";
scr.src = host + "/j/roundtrip.js";
document.documentElement.firstChild.appendChild(scr);
((document.getElementsByTagName('head') || [null])[0] || document.getElementsByTagName('script')[0].parentNode).appendChild(scr);
if(oldonload){oldonload()}};
}());
</script>
Expand Down
3 changes: 2 additions & 1 deletion lib/analytical/modules/google.rb
Expand Up @@ -18,6 +18,7 @@ def init_javascript(location)
#{"_gaq.push(['_setDomainName', '#{options[:domain]}']);" if options[:domain]}
#{"_gaq.push(['_setAllowLinker', true]);" if options[:allow_linker]}
#{"_gaq.push(['_setSiteSpeedSampleRate', #{options[:sample_rate]}]);" if options[:sample_rate]}
#{"_gaq.push(['_require', 'inpage_linkid', '//www.google-analytics.com/plugins/ga/inpage_linkid.js']);" if options[:enhanced_link_attribution]}
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
Expand Down Expand Up @@ -118,4 +119,4 @@ def track_trans

end
end
end
end
39 changes: 39 additions & 0 deletions lib/analytical/modules/google_universal.rb
@@ -0,0 +1,39 @@
module Analytical
module Modules
class GoogleUniversal
include Analytical::Modules::Base

def initialize(options={})
super
@tracking_command_location = :head_append
end

def init_javascript(location)
init_location(location) do
js = <<-HTML
<!-- Analytical Init: Google Universal -->
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', '#{options[:key]}', '#{options[:domain]}');
ga('send', 'pageview');
</script>
HTML
js
end
end

def event(name, *args)
data = args.first || {}
data = data[:value] if data.is_a?(Hash)
data_string = !data.nil? ? ", #{data}" : ""
"_gaq.push(['_trackEvent', \"Event\", \"#{name}\"" + data_string + "]);"
"ga('send', 'event', \"Event\", \"#{name}\"" + data_string + ");"
end
end
end
end
24 changes: 18 additions & 6 deletions lib/analytical/modules/hubspot.rb
Expand Up @@ -5,24 +5,36 @@ class Hubspot

def initialize(options={})
super
check_hub_id
@tracking_command_location = :body_append
end

def init_javascript(location)
init_location(location) do
js = <<-HTML
<!-- Analytical Init: Hubspot -->
<script type="text/javascript" language="javascript">
var hs_portalid=#{options[:portal_id]};
var hs_salog_version = "2.00";
var hs_ppa = "#{options[:domain]}";
document.write(unescape("%3Cscript src='" + document.location.protocol + "//" + hs_ppa + "/salog.js.aspx' type='text/javascript'%3E%3C/script%3E"));
<script type="text/javascript">
(function(d,s,i,r) {
if (d.getElementById(i)){return;}
var n=d.createElement(s),e=d.getElementsByTagName(s)[0];
n.id=i;n.src='//js.hubspot.com/analytics/'+(Math.ceil(new Date()/r)*r)+'/#{options[:hub_id]}.js';
e.parentNode.insertBefore(n, e);
})(document,"script","hs-analytics",300000);
</script>
HTML
js
end
end

private

def check_hub_id
if options[:hub_id].nil?
raise ArgumentError, "Hubspot tracking requires 'hub_id' to be set in the 'analytical.yml' config file; " +
"'portal_id' and 'domain' are no longer used."
end
end

end
end
end
end
69 changes: 66 additions & 3 deletions lib/analytical/modules/mixpanel.rb
Expand Up @@ -8,6 +8,24 @@ def initialize(options={})
@tracking_command_location = :body_append
end

# Mixpanel-specific queueing behavior, overrides Base#queue
def queue(*args)
return if @options[:ignore_duplicates] && @command_store.include?(args)
if args.first==:alias_identity
@command_store.unshift args
elsif args.first==:identify
if @command_store.empty?
@command_store.unshift args
else
first_command = @command_store.first
first_command = first_command.first if first_command.respond_to?(:first)
@command_store.unshift args unless first_command == :alias_identity
end
else
@command_store << args
end
end

def init_javascript(location)
init_location(location) do
js = <<-HTML
Expand All @@ -23,16 +41,45 @@ def init_javascript(location)
'track_forms','register','register_once','unregister','identify','alias','name_tag',
'set_config','people.set','people.increment','people.track_charge','people.append'];
for(e=0;e<h.length;e++)d(g,h[e]);a._i.push([b,c,f])};a.__SV=1.2;})(document,window.mixpanel||[]);
mixpanel.init("#{options[:key]}");
var config = { track_pageview: #{options.fetch(:track_pageview, true)} };
mixpanel.init("#{options[:key]}", config);
</script>
HTML
js
end
end

def track(event, properties = {})

# Examples:
# analytical.track(url_viewed)
# analytical.track(url_viewed, 'page name' => @page_title)
# analytical.track(url_viewed, :event => 'pageview')
#
# By default, this module tracks all pageviews under a single Mixpanel event
# named 'page viewed'. This follows a recommendation in the Mixpanel docs for
# minimizing the number of distinct events you log, thus keeping your event data uncluttered.
#
# The url is followed by a Hash parameter that contains any other custom properties
# you want logged along with the pageview event. The following Hash keys get special treatment:
# * :callback => String representing javascript function to callback
# * :event => overrides the default event name for pageviews
# * :url => gets assigned the url you pass in
#
# Mixpanel docs also recommend specifying a 'page name' property when tracking pageviews.
#
# To turn off pageview tracking for Mixpanel entirely, initialize analytical as follows:
# analytical( ... mixpanel: { key: ENV['MIXPANEL_KEY'], track_pageview: false } ... )
def track(*args)
return if args.empty?
url = args.first
properties = args.extract_options!
callback = properties.delete(:callback) || "function(){}"
%(mixpanel.track("#{event}", #{properties.to_json}, #{callback});)
event = properties.delete(:event) || 'page viewed'
if options[:track_pageview] != false
properties[:url] = url
# Docs recommend: mixpanel.track('page viewed', {'page name' : document.title, 'url' : window.location.pathname});
%(mixpanel.track("#{event}", #{properties.to_json}, #{callback});)
end
end

# Used to set "Super Properties" - http://mixpanel.com/api/docs/guides/super-properties
Expand All @@ -47,9 +94,25 @@ def identify(id, *args)
%(mixpanel.identify('#{id}');#{name_str})
end

# See https://mixpanel.com/docs/integration-libraries/using-mixpanel-alias
# For consistency with KissMetrics this method accepts two parameters.
# However, the first parameter is ignored because Mixpanel doesn't need it;
# pass any value for the first parameter, e.g. nil.
def alias_identity(_, new_identity)
%(mixpanel.alias("#{new_identity}");)
end

def event(name, attributes = {})
%(mixpanel.track("#{name}", #{attributes.to_json});)
end

def person(attributes = {})
%(mixpanel.people.set(#{attributes.to_json});)
end

def revenue(charge, attributes = {})
%(mixpanel.people.track_charge(#{charge}, #{attributes.to_json});)
end

end
end
Expand Down
40 changes: 40 additions & 0 deletions lib/analytical/modules/mouseflow.rb
@@ -0,0 +1,40 @@
module Analytical
module Modules
class Mouseflow
include Analytical::Modules::Base

def initialize(options={})
super
check_js_url
@tracking_command_location = :body_append
end

def init_javascript(location)
init_location(location) do
js = <<-HTML
<!-- Analytical Init: Mouseflow -->
<script type="text/javascript">
var _mfq = _mfq || [];
(function() {
var mf = document.createElement("script"); mf.type = "text/javascript"; mf.async = true;
mf.src = "#{options[:js_url]}";
document.getElementsByTagName("head")[0].appendChild(mf);
})();
</script>
HTML
js
end
end

private

def check_js_url
if options[:js_url].nil?
raise "You didn't provide a js_url for mouseflow. " +
"Add one to your analytical.yml file so Mouseflow will work."
end
end

end
end
end

0 comments on commit 5aa2f92

Please sign in to comment.