Giter Site home page Giter Site logo

analytical's Introduction

Analytical

Gem for managing multiple analytics services in your rails app.

<img src=“https://secure.travis-ci.org/jkrall/analytical.png” />

Service implementations include:

Usage

Add the following to your controllers:

analytical

Add a configuration file (config/analytical.yml) to declare your API keys, like so:

production:
  google:
    key: UA-5555555-5
  clicky:
    key: 55555
development:
test:

You can add different configurations for different environments.

By default, all the declared analytics modules are loaded. You can override this behavior in the controller.

analytical :modules=>[:console, :google, :clicky]

Then, in your template files, you’ll want to add the analytical helper methods for initializing the tracking javascript:

<!DOCTYPE html>
<html>
  <head>
    <%= raw analytical.head_prepend_javascript %>
    <title>Example</title>
    <%= stylesheet_link_tag :all %>
    <%= javascript_include_tag :defaults %>
    <%= csrf_meta_tag %>
    <% analytical.identify '5', :email=>'[email protected]' %>
    <%= raw analytical.head_append_javascript %>
  </head>
  <body>
    <%= raw analytical.body_prepend_javascript %>
    <%= yield %>
    <%= raw analytical.body_append_javascript %>
  </body>
</html>

Note the example above also includes an identify() command that will apply to every page. More likely, you’ll want to make this identify() command conditional so that it only applies when you have a logged-in user:

<% analytical.identify(current_user.id, :email=>current_user.email) if current_user %>

You can sprinkle the track() and event() tracking methods throughout your views & controllers as needed.

analytical.track '/a/really/nice/url'
analytical.event 'Some Awesome Event', :with=>:data

It’s possible to conditionally disable analytics by specifying a ‘disable_if` method.

analytical :disable_if => lambda{ |controller| controller.i_can_haz_tracking? }

Analytical also provides the ability to filter your active modules dynamically:

analytical :filter_modules => lambda{ |controller, modules|
  controller.use_google_analytics? ? modules : modules - [:google]
}

This can be useful for enabling the console logger optionally in your app, based on a request parameter:

:filter_modules => lambda { |controller, modules|
  controller.use_console_logger? ? [:console] : modules
}

You can also configure modules in the controller by passing a hash to the :modules option

analytical :modules => { :google => { key: 'UA-5555555-5' } }

Finally it is also possible to dynamically specify what modules to use and their configurations, which can come in handy if your site uses multi-tenancy, where every tenant might not wish to use the same modules or configurations for each module.

analytical :modules => lambda{ |controller| controller.analytical_modules }

In this case we would then implement a method in the controller that could look like this:

def analytical_modules
  case current_tenant.name.parameterize
  when "site-1"
    {
      :google => { key: 'UA-5555555-5' }
    }
  when "site-2"
    {
      :google => { key: 'UA-1111111-1' }
    }
  end
end
hide_action :analytical_modules

Adding new modules

New modules should be fairly easy to add. Follow the structure that I’ve used in the Clicky, Google, and KISSMetrics modules… and you should be fine. All modules should include the Analytical::Base::Api module, so that they have some default behavior for methods that they don’t support or need.

Session-based command queues

By default, any Analytical commands that are queued in a controller that subsequently redirects won’t be emitted to the client. This is because the redirect triggers a new request, and everything is cleared out at the beginning of each request.

However, if you would like to be able to queue commands between requests… there’s a new option that supports this behavior:

analytical :modules=>[:console, :google], :use_session_store=>true

This will store the queued commands in the user session, clearing them out when they are emitted to the client, but allowing you to make calls like:

analytical.track 'something'

… in your controller. After a redirect, the corresponding track() call will be emitted in the next request made by the client. NOTE: This is new and somewhat experimental, and could cause problems if you store large amounts of data in the session. (there is a 4k limit to session data)

Javascript tracking/event commands

Sometimes you want to trigger an analytics track/event via javascript. Analytical now provides a solution for this by default. Appended to your <head> is a simple javascript object that will contain “instantaneous” versions of the tracking commands for each of your modules.

You call these analytical commands like this:

<script type="text/javascript">Analytical.track('/some/url');</script>
<script type="text/javascript">Analytical.event('A javascript event', {with: 'data'});</script>

When you call these commands, it will pass the track/event name & data on to each of the modules. (Take a look at the simple javascript helpers in your <head> for more information.)

To disable this functionality, use

analytical :javascript_helpers => false

Note on Patches/Pull Requests

I would be extremely happy to accept contributions to this project! If you think something should work differently, send me a message and I’d love to discuss your ideas. Even better:

  • Fork the project.

  • Make your feature addition or bug fix.

  • Add specs for it. This is important so I don’t break it in a future version unintentionally.

  • Commit, do not mess with rakefile, version, or history. (if you want to have your own version, that is fine but bump version in a commit by itself I can ignore when I pull)

  • Send me a pull request. Bonus points for topic branches.

Current Contributors

These fine folks have contributed patches and new features to this project:

Thanks guys!

Copyright © 2010 Joshua Krall. See LICENSE for details.

analytical's People

Contributors

bryanl avatar clupprich avatar dblock avatar dipth avatar freerobby avatar gib avatar indirect avatar jellybob avatar jkrall avatar johnpaulashenfelter avatar kamilski81 avatar mathieuravaux avatar mattvanhorn avatar mdurn avatar nirvdrum avatar npalrecha avatar nwp avatar olauzon avatar oshoma avatar rajiv avatar scudco avatar sfsekaran avatar shiftb avatar soulnafein avatar unlimit avatar yachi avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

analytical's Issues

Add MixPanel

Would be nice to add MixPanel support as well.

CrazyEgg module assumes string, gets fixnum and raises exception

My key is like: 12345678

The crazy egg module does this:

code_url = "#{options[:key][0,4]}/#{options[:key][4,4]}"

which would work if "key" is a String, but YAML reads the key as a Fixnum and throws:
wrong number of arguments (2 for 1)
analytical-2.6.0/lib/analytical/modules/crazy_egg.rb:13:in `[]'

calling "to_s" before the indexing should fix. There are no specs for this module or I would have just submitted a patch. Instead I hacked a workaround by appending "xxx" to my key to force it to be a String.

Kissmetrics are not working with turbolinks/jquery mobile

I tested Analytical for KissMetrics implementation in my project, which

The Issue is: Events are triggered from controllers, but there is need to refresh the page, to reload javascript code in head tags after calling analytical.event method.

When websites uses page.on 'load' or page.on 'pageshow' events, kissmetrics doesn't trigger any event.

It should be a way to reload script after Turbolinks/jQuery Mobile events.

Difficulty in adding console module in analytical

This is going way back, but in 2.11.0 the declarative configuration options for :modules and :development_modules were replaced by an environment-based setup in the analytical.yml file. A consequence of this is it's way too hard to log to the console. The console is one of the best things about analytical because I can see what's happening as things get processed. The reason for the difficulty is two-fold:

  1. There's no natural configuration for the console. Just adding a key to the analytical.yml file doesn't work because the config parser explicitly looks for hashes. So, something like this won't work:
development:
  console:

But something like this will:

development:
  console:
    garbage: true

This is neither documented nor expected. An explicit configuration line might make more sense, but may break with the backwards-compatible file processor.

  1. The next most common way to configure the console is to add it to the :modules list when declaratively configuring analytical. Unfortunately, this now only works if every environment uses the exact same modules. Many providers don't have sandboxes so they must be left out of all environments except production. Since the :development_modules option no longer exists, the lowest common denominator must be used or all modules must be sourced from the configuration file, leading back to the first problem.

It seems unlikely that the change in 2.11 will be rolled back now, as it's been in place for the entire life of the 3.x series. So, feedback on how to deal with this would be appreciated. I'm happy to help out any way I can.

Analytical helper not loading in rails

We had been using the analytical gem circa version 2 and recently upgraded to 3.0.12. It appears that the view helper wasn't loading correctly, giving the following error:
undefined local variable or method 'analytical' for #<#<Class:0x10a261b18>:0x10a251560>

Adding helper_method :analytical to our application_controller.rb fixed this issue. We are on rails 3.1.3.

analytical 2.7 broke Rails 3 support

Starting with analytical 2.7, there are a lot more dependencies listed in the gemspec. My guess is these were added by one of the new modules. In any event, analytical now only works with Rails 2.x, for x >= 3 and will not load up in Rails 3.

Rails 3.0.9 dependency

Is there any reason this gem has a dependency on Rails 3.0.9? Does this mean if I'm running Rails 3.2.7 installing this gem will also install Rails 3.0.9?

GA Event category should not be hardcoded to "Event"

HI first thanks for this great gem. I noticed that the google_universal support is only available on the master branch and not in any of the release branches. Is there an ETA when it will be officially released. Also, the event tracking api as implemented doesn't fully match google's spec.
https://developers.google.com/analytics/devguides/collection/analyticsjs/events

The current implementation hard codes the category as "Event", and doesn't support the last number parameter. I'm happy to provide a pull request with the desired enhancements but just wanted to check to make sure I didn't miss anything.

RSpec view failures

In my view specs, templates that included calls to analytical.event were causing exceptions. It turns out this was because ActionView::TestCase::TestController wasn't inheriting the call to analytical that I put in my ApplicationController. The easiest fix I found was adding this to my spec_helper.rb:

    # Give TestController an empty list of analytical modules
    ActionView::TestCase::TestController.class_eval do
      self.analytical_options = {:modules => []}
    end

Seems like it might be nice for Analytical to provide RSpec integration so that this doesn't have to be debugged and then added by hand. Thanks!

Support sessionizing the analytical command queue

I have a fair idea of how to do this thanks to iconara's snogmetrics (http://github.com/iconara/snogmetrics), but I was curious what you had to say on this topic. I'd really like to be able to call "analytical.event('foo')" in a controller that ends up redirecting without losing that event or having to use the server-side implementation (blegh!).

  • The command queue should be (optionally?) stored in a session variable
  • When analytical emits the javascript the session variable should be cleared

Thoughts?

Print warning if :development_modules is still used

I'm really late to the game on this one, but I've just now realized that :development_modules does nothing since version 2.11.0. As a result, I've been storing crap data in my various analytics providers for over a year. Naturally, this is problematic and broke pretty heavily with the backwards compatibility note in the README.

Inject analytics javascript using Rack

Just a quick idea, which I may or may not have time to hack on at some point. It would be really neat if I could avoid having to add all the [head|body]_[prepend|append]_javascript calls in my layout by having a Rack middleware which injects them as the response goes out.

Add a changelog

It'd be very helpful if there were a changelog indicating what's different from release-to-release. I'm looking to upgrade an app from Rails 2.3 -> 3.0 and I can't tell which version of analytical I should target. The latest doesn't work with Rails 3 and appears not have for for several versions now. Beyond that, it'd help let me know whether a new release is worth upgrading to or not.

SessionCommandStore broken

I've only managed to test on Rails 3.2, but it looks like SessionCommandStore has been broken since 9b0833e was introduced. The core problem is the config file is now loaded as a HashWithIndifferentAccess, rather than as a simple hash. HashWithIndifferentAccess ensures any hash values are also types of HashWithIndifferentAccess. In order to do so, it must make a new copy of the value. In this case, the value is the session, which is a hash. Creating a new session with indifferent access creates a new hash that is no longer associated with the session, so all modifications are now on an in-memory copy.

TrackSubmit

Hi,

First, thanks for the gem. It's pretty awesome.

I'm using KissMetrics and would like to call TrackSubmit. I don't see a way to do that with the current code base. It seems pretty easy to add. If I add TrackSubmit to KissMetrics, and perhaps the corollary track_forms to MixPanel, would you accept the pull request?

Thanks,
Gabe

undefined method `merge' for nil:NilClass

Hi,

I have installed the gem

and I have been trying to call the methods .identify and .track but get undefined method `merge' for nil:NilClass.

In my config/analytical.yml I have the following:

production:
kiss_metrics:
js_url_key: '//doug1izaerwt3.cloudfront.net/MYKEY.js'

I have been following https://github.com/gyarra/analytical/wiki/KissMetrics but I am only on step 2.

I am using rails 4.0.1.

Anyone able to provide me some direction or point out where I am going wrong? Do let me know if you need more information.

Use analytical in mailers or models

It would be nice if analytical could be used from mailers and models in the same way as from controllers and views, too.
Update:
OK, after studying the code of the analytical gem I realized that all the tracking commands are called via javascript on the client side. Even for tracking commands in the controllers...
But even so I feel that it would be possible to make it work for models and mailer by using a library like http_party and a queue to make calls from the server side.
Would be interesting to know what others think about this....

New rubygem release

I was wondering if there could be a new rubygem release since there have been a good amount of changes since the last release. I'm fine using the commit sha for now, but it would be handy.

Thanks!

analytical.head_prepend_javascript raises "undefined method `merge' for nil:NilClass"

Added to config/analytical.yml:

production:
development:
kissmetrics:
key: XXXXXXXX
mixpanel:
key: XXXXXXXX

And added the following to my controller:
analytical :use_session_store => true

Added the following to my site's layout, in <head>:
<%= raw analytical.head_prepend_javascript %>

I followed the README, any idea what I might be doing wrong?

Maintainer

So, you guys are looking for one right?

I can help. I currently maintain carrierwave and minimagick and I'm in a project that uses analytical.

BUG: unitialized constant Analytical::Modules::Production

Hey,

I discovered a really annoying bug when you create the analytical.yml file exactly according to the readme, like this:

production:
google:
key: UA-5555555-5
clicky:
key: 55555

This will give the error:

uninitialized constant Analytical::Modules::Production

or

uninitialized constant Analytical::Modules::Kissmetrics

when calling the "analytical" helper from a controller or a view.

The error is resolved when removing the space before the API-keys, so the file looks like this:

production:
google:
key:UA-5555555-5
clicky:
key:55555

This is a very annoying bug, since it's almost impossible to detect.
I hope you're able to fix it soon.

PS: I would suggest to update the Readme in the meanwhile, so more people don't unnecessarily run into it by following the setup procedure there.

Cheers.

Rails 3.1 fix doesn't work in Rails 3.2

In lib/analytical/api.rb there is a check for Rails 3.1 like so: if ::Rails::VERSION =~ /^3\.1/

The same Rails 3.1 codepath should probably be run for all versions > 3.1, but the check as it is will only work with 3.1.x. So Rails 3.2 executes the old path and raises a bunch of deprecation warnings.

Missing partial analytical_javascript.html

Rails 3.0.9, analytical 3.0.6.

    ActionView::Template::Error (Missing partial /home/dblock/.rvm/gems/ruby-1.9.2-p180/gems/analytical-3.0.6/app/views/application/analytical_javascript.html with {:handlers=>[:erb, :rjs, :builder, :rhtml, :rxml, :haml], :formats=>[:html], :locale=>[:en, :en]} in view paths "/home/dblock/source/gravity/dblock/app/views", "/home/dblock/source/gravity/dblock/vendor/plugins/country_select/app/views", "/home/dblock/.rvm/gems/ruby-1.9.2-p180/gems/analytical-3.0.6/app/views", "/home/dblock/.rvm/gems/ruby-1.9.2-p180/gems/devise_invitable-0.5.2/app/views", "/home/dblock/.rvm/gems/ruby-1.9.2-p180/gems/devise-1.4.2/app/views", "/home/dblock/.rvm/gems/ruby-1.9.2-p180/gems/kaminari-0.12.4/app/views"):
        9:     = include_stylesheets :ipad if ipad_device?
        10:     = include_stylesheets :edit_artwork if current_user.has_authorization_to?(:update, Artwork)
        11:     
        12:     = raw analytical.head_append_javascript
        13: 
        14:   %body
        15:     = raw analytical.body_prepend_javascript
      app/views/layouts/client/main.html.haml:12:in `_app_views_layouts_client_main_html_haml__428043036_126237760__535360229'
      app/controllers/application_controller.rb:32:in `block (3 levels) in <class:ApplicationController>'
      app/controllers/application_controller.rb:31:in `block in <class:ApplicationController>'`

track on a redirect_to seems to get discarded

def create
  <do stuff>
  if something.save
    analytical.track('It Saved!')
    redirect_to 'somewhere/else'
  else
    ...
  end
end

The track seems to get discarded/lost in this case. Is that a known issue, unknown issue, or a feature?

Differences between gem and source

Hi,

I noticed some differences between the code in the gem and the code on Github. It appears that the gem code is more current, although both say they are version 3.0.12. I'm happy to merge in code from the gem that seems more up to date.

modules/mixpanel.rb

  • In the gem, the mixpanel JS library is correctly referenced by the correct name, mpmetrics. In the source it's referenced mixpanel - not actually the JS lib name.
  • The gem links to the JS library from api.mixpanel.com, so it will automatically get updates. The git code includes a hard-coded JS library that may be out of date.

modules/kissmetrics.rb

3 differences

modules/google.rb

2 differences

api.rb

3 differences.

Just say the word and I'm happy to jump in.

Thanks!
Gabe

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.