Apply Google Analytics Tracking to YARD Documentation
Overview
The yard generated documentation does not provide a way to specify the Google
Analytics tracking ID in the configuration. If you want to have the tracking ID
in the generated documentation, you have to go through all the files and inject
the script. Also the files change every time the documentation is generated. I
use the yard-generated documentation as the website for my
jenkins_api_client project
and want to use my Google Analytics tracking ID to see the usage of the
project. So I decided to create a rake task that will do this for me
The Rake Task
This simple rake task will go through all html files in the subdirectories of
current directory and inject the google analytics tracking script. Include this
rake task in your Rakefile and replace UA-XXXXXXXX-X with the google
analytics tracking ID of your website.
task:apply_google_analyticsdo# The string to replace in the html document. This is chosen to be the end# body </body> tag. So the script can be injected as the last thing in the# document body.string_to_replace="</body>"# This is the string to replace with. It include the google analytics script# as well as the end </body> tag.string_to_replace_with=<<-EOF <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-XXXXXXXX-X']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> </body> EOFfiles=Dir.glob("**/*.html")files.eachdo|html_file|puts"Processing file: #{html_file}"contents=""# Read the file contentsfile=File.open(html_file)file.each{|line|contents<<line}file.close# If the file already has google analytics tracking info, skip it.ifcontents.include?(string_to_replace_with)puts"Skipped..."nextend# Apply google analytics tracking info to the html filecontents.gsub!(string_to_replace,string_to_replace_with)# Write the contents with the google analytics info to the filefile=File.open(html_file,"w")file.write(contents)file.closeendend
Since this is newly generated documentation, the file has to go through all
files inject the google analytics script in all of them. If the file already
has the analytics script, that file will be skipped. A generated page using
this rake task can be found in the
jenkins_api_client project
documentation here.