#! /usr/bin/env ruby
#
# this simple output filter can append the require google analytics
# javascript, or any javascript for that matter, to ever html page served by
# your site dynamically without needing to edit those files. see
#
#   http://httpd.apache.org/docs/2.2/mod/mod_ext_filter.html
#
# for details 
#

html = STDIN.read

google_analytics_code = "UA-xxxxxxx-2"

javascript = <<-javascript

  <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">
    var pageTracker = _gat._getTracker("#{ google_analytics_code }");
    pageTracker._initData();
    pageTracker._trackPageview();
  </script>

javascript

html.sub!( %r'((?:\<\s*/html\s*\>\s*)\z)'i, javascript + '\1' )

STDOUT.write html



__END__

### a sample httpd.conf configuration
### assuming this script is installed in /bin/google-analytics

ExtFilterDefine google-analytics mode=output intype=text/html outtype=text/html cmd="/bin/google-analytics"

<Directory />

  SetOutputFilter google-analytics

</Directory>