drhenner/ror_ecommerce

View on GitHub
app/views/shared/_google_analytics.html.erb

Summary

Maintainability
Test Coverage
<% tracker = Settings.google.analytics_code %>
<% if tracker %>
  <script type="text/javascript">
    var _gaq = _gaq || [];
    _gaq.push(['_setAccount', '<%= tracker %>']);
    _gaq.push(['_setDomainName', 'ufcfit.com']);
    _gaq.push(['_setAllowLinker', true]);

    <% if flash[:analytics] -%>
      _gaq.push(['_trackPageview', '<%=flash[:analytics]%>']);
    <% else -%>
      _gaq.push(['_trackPageview']);
    <% end -%>

    (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);
    })();

    <% if customer_confirmation_page_view && @order %>
      // report e-commerce transaction information when applicable
      _gaq.push(['_addTrans',
        '<%= @order.try(:number) %>', //Order Number
        '', //Affiliation
        '<%= @order.try(:find_total).try(:to_f) %>', //Order total
        '<%= @order.try(:total_tax_charges).try(:to_f) %>', //Tax Amount
        '<%= @order.try(:shipping_charges) %>', //Ship Amount
        '<%= @order.try(:ship_address).try(:city) %>', //City
        '<%= @order.try(:ship_address).try(:display_state_name) %>', //State
        ''  //Country
      ]);

      <% @order.order_items.each do |order_item| -%>
        _gaq.push(['_addItem',
          '<%= @order.try(:number) %>',
          '<%= order_item.try(:variant).try(:sku) %>',
          '<%= order_item.try(:variant).try(:product_name) %>',
          '', // category or variation
          '<%= order_item.try(:price) %>',
          '1'
        ]);
      <% end %>

      _gaq.push(['_trackTrans']);
    <% end %>

    $(document).on('click', ' a.checkout-button', function() {
      _gaq.push(['_trackEvent', 'beginCheckout', 'clicked'])
    });
    $(document).on('click', ' a.add-to-cart-button', function() {
      _gaq.push(['_trackEvent', 'addToCart', 'clicked'])
    });
  </script>
<% end %> <%# END if tracker %>