|  |  | @@ -23,6 +23,10 @@ class Event < ActiveRecord::Base | 
            
            
              | 23 | 23 |      where("events.created_at > ?", timespan) | 
            
            
              | 24 | 24 |    } | 
            
            
              | 25 | 25 |   | 
            
            
              |  | 26 | +  scope :expired, lambda { | 
            
            
              |  | 27 | +    where("expires_at IS NOT NULL AND expires_at < ?", Time.now) | 
            
            
              |  | 28 | +  } | 
            
            
              |  | 29 | + | 
            
            
              | 26 | 30 |    after_create :possibly_propagate | 
            
            
              | 27 | 31 |   | 
            
            
              | 28 | 32 |    # Emit this event again, as a new Event. | 
            
            
            
            
              |  |  | @@ -33,8 +37,8 @@ class Event < ActiveRecord::Base | 
            
            
              | 33 | 37 |    # Look for Events whose `expires_at` is present and in the past.  Remove those events and then update affected Agents' | 
            
            
              | 34 | 38 |    # `events_counts` cache columns.  This method is called by bin/schedule.rb periodically. | 
            
            
              | 35 | 39 |    def self.cleanup_expired! | 
            
            
              | 36 |  | -    affected_agents = Event.where("expires_at IS NOT NULL AND expires_at < ?", Time.now).group("agent_id").pluck(:agent_id) | 
            
            
              | 37 |  | -    Event.where("expires_at IS NOT NULL AND expires_at < ?", Time.now).delete_all | 
            
            
              |  | 40 | +    affected_agents = Event.expired.group("agent_id").pluck(:agent_id) | 
            
            
              |  | 41 | +    Event.expired.delete_all | 
            
            
              | 38 | 42 |      Agent.where(:id => affected_agents).update_all "events_count = (select count(*) from events where agent_id = agents.id)" | 
            
            
              | 39 | 43 |    end | 
            
            
              | 40 | 44 |   |