lib/mixpanel/tracker.rb in mixpanel-1.1.3 vs lib/mixpanel/tracker.rb in mixpanel-2.0.0

- old
+ new

@@ -4,22 +4,45 @@ require 'thread' require 'mixpanel/tracker/middleware' module Mixpanel class Tracker - def initialize(token, env, async = false, url = 'http://api.mixpanel.com/track/?data=') + def initialize(token, env, options={}) @token = token @env = env - @async = async - @url = url - clear_queue + @async = options.fetch(:async, false) + @url = options.fetch(:url, 'http://api.mixpanel.com/track/?data=') + @persist = options.fetch(:persist, false) + + if @persist + @env["rack.session"]["mixpanel_events"] ||= [] + else + clear_queue + end end def append_event(event, properties = {}) append_api('track', event, properties) end + def append_person_event(properties = {}) + # evaluate symbols and rewrite + special_properties = %w{email created first_name last_name last_login username country_code} + special_properties.each do |key| + symbolized_key = key.to_sym + if properties.has_key?(symbolized_key) + properties["$#{key}"] = properties[symbolized_key] + properties.delete(symbolized_key) + end + end + append_api('people.set', properties) + end + + def append_person_increment_event(property, increment=1) + append_api('people.increment', property, increment) + end + def append_api(type, *args) queue << [type, args.map {|arg| arg.to_json}] end def track_event(event, properties = {}) @@ -39,14 +62,22 @@ "" end end def queue - @env["mixpanel_events"] + if @persist + return @env["rack.session"]["mixpanel_events"] + else + return @env["mixpanel_events"] + end end def clear_queue - @env["mixpanel_events"] = [] + if @persist + @env["rack.session"]["mixpanel_events"] = [] + else + @env["mixpanel_events"] = [] + end end class <<self WORKER_MUTEX = Mutex.new