Google analytics

In this example we will add google analytics code to our web site.

 

Google analytics code is normally added at the end of design source.

 <%= dc_render(:dc_common, method: 'google_analytics', code: 'UA-12345678-1'%>
 

Source code for google_analytics method can be found in dc_common_renderer.rb source file. 

def google_analytics
  ga_acc = @opts[:code] || @opts[:ga_acc]
  return '' if ga_acc.nil?
  html =<<EOT
<!-- Google analytics. -->
<script type="text/javascript">
  (function(i,s,o,g,r,a,m){
  if (typeof(eu_cookies_allowed) === "function" && !eu_cookies_allowed() ) return;

  i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

  if (typeof(ga) === "function") {
    ga('create', '#{ga_acc}', 'auto');
    ga('send', 'pageview')
  }
</script>
EOT
  html.html_safe
end

 

Passing code parameter is call is optional. It is more convenient to set ga_acc value in settings field of dc_site or dc_page document. GA code is accessed In renderer as @opts[:ga_acc]. GA code defined in site document is valid for whole site. When you want to follow access to single page define ga_acc in page document. 

 

Settings fields have values defined as yaml. This is example of common settings from dc_site document.

html_editor: ckeditor
file_select: elfinder
ckeditor:
 config_file: /files/ck_config.js
 css_file: /files/ck_css.css

ga_acc: UA-12345678-6

 

Rest of the code is more or less copy+paste from code that Google suggests with the exception of eu_cookies_allowed function which is called if defined and code flow is interrupted if function returns false.


Last update: 08.05.2018