event.rb 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. require 'json_serialized_field'
  2. # Events are how Huginn Agents communicate and log information about the world. Events can be emitted and received by
  3. # Agents. They contain a serialized `payload` of arbitrary JSON data, as well as optional `lat`, `lng`, and `expires_at`
  4. # fields.
  5. class Event < ActiveRecord::Base
  6. include JSONSerializedField
  7. attr_accessible :lat, :lng, :payload, :user_id, :user, :expires_at
  8. acts_as_mappable
  9. json_serialize :payload
  10. belongs_to :user
  11. belongs_to :agent, :counter_cache => true, :touch => :last_event_at
  12. scope :recent, lambda { |timespan = 12.hours.ago|
  13. where("events.created_at > ?", timespan)
  14. }
  15. after_create :possibly_propagate
  16. # Emit this event again, as a new Event.
  17. def reemit!
  18. agent.create_event :payload => payload, :lat => lat, :lng => lng
  19. end
  20. # Look for Events whose `expires_at` is present and in the past. Remove those events and then update affected Agents'
  21. # `events_counts` cache columns. This method is called by bin/schedule.rb periodically.
  22. def self.cleanup_expired!
  23. affected_agents = Event.where("expires_at IS NOT NULL AND expires_at < ?", Time.now).group("agent_id").pluck(:agent_id)
  24. Event.where("expires_at IS NOT NULL AND expires_at < ?", Time.now).delete_all
  25. Agent.where(:id => affected_agents).update_all "events_count = (select count(*) from events where agent_id = agents.id)"
  26. end
  27. protected
  28. def possibly_propagate
  29. #immediately schedule agents that want immediate updates
  30. propagate_ids = agent.receivers.where(:propagate_immediately => true).pluck(:id)
  31. Agent.receive!(:only_receivers => propagate_ids) unless propagate_ids.empty?
  32. end
  33. end