Created
January 11, 2012 18:53
-
-
Save bryfox/1596169 to your computer and use it in GitHub Desktop.
Sinatra port of Percent Mobile's rails helper for analytics
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'sinatra/base' | |
require 'cgi' | |
module Sinatra | |
# http://code.percentmobile.com/snippet/ruby_on_rails/percent_mobile/lib/percent_mobile_helper.rb | |
module PercentMobileHelper | |
PERCENT_MOBILE_COOKIE_PATH="/" | |
PERCENT_MOBILE_VISIT_DURATION=60*60 | |
PERCENT_MOBILE_VERSION="rails_26062010" | |
PERCENT_MOBILE_COOKIE_NAME="_percent_mobile_c" | |
def percent_mobile_track(id,url="") | |
percent_mobile_u=new_random | |
percent_mobile_v=new_random | |
if request.cookies[:PERCENT_MOBILE_COOKIE_NAME] and request.cookies[:PERCENT_MOBILE_COOKIE_NAME]=~/(\d+)[01]_(\d+)_(\d+)[01]/ | |
percent_mobile_u=$1+"0"; | |
percent_mobile_v=$3+"0" if $2.to_i>Time.new().to_i | |
end | |
response.set_cookie(PERCENT_MOBILE_COOKIE_NAME, { | |
:value=>percent_mobile_u+'_'+(Time.new().to_i+PERCENT_MOBILE_VISIT_DURATION).to_s+'_'+percent_mobile_v, | |
:expires=> Time.now + 365 * 24 * 60 * 60, | |
:path=>PERCENT_MOBILE_COOKIE_PATH | |
}) | |
subdomain="" | |
# for _subdomain in request.subdomains | |
# subdomain+=_subdomain+"." | |
# end | |
url = request.scheme+'://'+subdomain+request.host+request.fullpath if url=="" | |
referer="" | |
referer = request.env["HTTP_REFERER"] if request.env["HTTP_REFERER"] | |
image_url="#{request.scheme}://tracking.percentmobile.com/pixel/#{id}/#{rand(0xffff)}.gif?v=#{PERCENT_MOBILE_VERSION}&us=#{percent_mobile_u}&vi=#{percent_mobile_v}&url=#{CGI::escape(url)}&referer=#{CGI::escape(referer)}"; | |
if request.env["HTTP_USER_AGENT"] and request.env["HTTP_USER_AGENT"]=~/iPhone/ | |
return "<script type='text/javascript'> | |
<!-- | |
{ | |
var m='';var s=document.createElement('style');var d=document.createElement('div');d.id='pm_IS_#{id}'; | |
s.innerText='@media (-webkit-min-device-pixel-ratio:2) {#'+d.id+'{display:none !important;}}'; | |
document.documentElement.appendChild(s).appendChild(d); | |
var r=getComputedStyle(d,null).getPropertyValue('display')=='none'; | |
s.parentNode.removeChild(s);d.parentNode.removeChild(d); | |
if(r){m='&m=4';}else{r=new Date().getTime();for(var s=0;new Date().getTime()-r<20;s++){Math.random();}m = '&m='+((s>1000)?'3':'2');} | |
new Image().src='#{image_url}'+m; | |
} | |
--> | |
</script>" | |
else | |
return "<img src='#{image_url.gsub('&','&')}' width='2' height='2' alt='.' />"; | |
end | |
end | |
private | |
def new_random | |
rand(2147583646).to_s+"1" | |
end | |
end | |
helpers PercentMobileHelper | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment