kivanio (owner)

Fork Of

Revisions

  • 1d1d4a spohlenz Sun Oct 11 16:34:28 -0700 2009
  • ca32fc Sun Oct 11 16:18:17 -0700 2009
gist: 227937 Download_button fork
public
Public Clone URL: git://gist.github.com/227937.git
Embed All Files: show embed
google_analytics.rb #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
module Rack
  class GoogleAnalytics
    TRACKING_CODE = <<-EOCODE
<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
try {
var pageTracker = _gat._getTracker("{{ID}}");
pageTracker._trackPageview();
} catch(err) {}</script>
EOCODE
    
    def initialize(app, id)
      @app = app
      @id = id
    end
    
    def call(env)
      status, headers, body = @app.call(env)
      
      body.each do |part|
        if part =~ /<\/body>/
          part.sub!(/<\/body>/, "#{tracking_code}</body>")
 
          if headers['Content-Length']
            headers['Content-Length'] = (headers['Content-Length'].to_i + tracking_code.length).to_s
          end
 
          break
        end
      end
      
      [status, headers, body]
    end
  
  private
    def tracking_code
      TRACKING_CODE.sub(/\{\{ID\}\}/, @id)
    end
  end
end