Created
November 17, 2011 07:31
-
-
Save kimoto/1372600 to your computer and use it in GitHub Desktop.
Google Analyticsのコードを</head>の直前に埋め込むプログラム
This file contains hidden or 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
| #!env ruby | |
| # | |
| # ganalytics.rb | |
| # | |
| # 詳細: | |
| # Google Analyticsのコードを</head>の直前に埋め込むコード | |
| # すでに埋め込まれてた場合は埋め込みません | |
| # | |
| # 使い方: | |
| # ruby ganalytics.rb Path UA-XXXXX-X | |
| # ruby ganalytics.rb ./hogehoge/piyo/test.html UA-XXXXX-X | |
| # | |
| # たくさんのファイルを一度に変換するにはこんな感じで: | |
| # find . -type f | egrep '*.html$' | fgrep -v './tank' | fgrep -v './paper.js' | xargs -n1 -I% ruby ./ganalytics.rb % "UA-XXXXXX-X" | |
| # | |
| def add_google_analytics_code(path, account) | |
| if path.nil? || path.empty? | |
| raise ArgumentError | |
| end | |
| if account.nil? || account.empty? | |
| raise ArgumentError | |
| end | |
| google_analytics_code = <<EOT | |
| <script type="text/javascript"> | |
| var _gaq = _gaq || []; | |
| _gaq.push(['_setAccount', '#{account}']); | |
| _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> | |
| EOT | |
| data = File.readlines(path) | |
| # already exist? | |
| if data.find{ |line| line.include? account } | |
| raise "already exist!" | |
| end | |
| # insert google analytics code | |
| result = "" | |
| data.each{ |line| | |
| if line =~ /<\/head>/ | |
| result += google_analytics_code | |
| end | |
| result += line | |
| } | |
| # rewrite | |
| File.open(path, "wb"){ |f| | |
| f.write(result) | |
| } | |
| end | |
| def main | |
| path = ARGV.shift | |
| account = ARGV.shift; | |
| add_google_analytics_code(path, account) | |
| end | |
| main |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment