class TrackableStat include MongoMapper::Document # MongoMapper Setup ============================================================================== many :trackable_sessions, :order => :created_at key :site, String, :index => true key :bounces, :default => 0 key :clickthroughs, :default => 0 key :conversions, :default => 0 key :duration, :default => 0 key :new_visits, :default => 0 key :organic_visits, :default => 0 key :pageviews, :default => 0 key :ppc_visits, :default => 0 key :direct_visits, :default => 0 key :return_visits, :default => 0 key :search_visits, :default => 0 key :visits, :default => 0 timestamps! # Scopes ========================================================================================= scope :by_site, lambda { |site| { :conditions => { :site => site } } } scope :by_date, lambda { |date| { :conditions => { :created_at => { '$gte' => date.beginning_of_month, '$lte' => date.end_of_month } } } } scope :for_date_range, lambda { |start_date,end_date| { :conditions => { :created_at => { '$gte' => start_date.beginning_of_month, '$lte' => end_date.end_of_month } } } } # Class Methods ================================================================================== def self.sites TrackableStat.all(:fields => :site).map{|s| s.site.downcase}.uniq end # Instance Methods =============================================================================== def touch(session, last_action, previous_action = nil) if previous_action.nil? # New session self.trackable_sessions << session self.clickthroughs += 1 if last_action.clickthrough? self.conversions += 1 if last_action.conversion? self.direct_visits += 1 if session.kind == 'direct' self.new_visits += 1 if session.new_visit self.organic_visits += 1 if session.kind == 'natural' self.pageviews += 1 self.ppc_visits += 1 if session.kind == 'paid' self.return_visits += 1 if ! session.new_visit self.search_visits += 1 if session.kind == 'search' self.visits += 1 self.bounces += 1 # Assume that it's a bounce until a second view is recorded else # Existing session self.clickthroughs += 1 if last_action.clickthrough? self.conversions += 1 if last_action.conversion? self.duration += last_action.created_at - previous_action.created_at self.pageviews += 1 if last_action.view? self.bounces -= 1 if session.trackable_actions.count == 2 end self.save end end