Nenhuma Descrição http://j1x-huginn.herokuapp.com

event.rb 1.9KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. include LiquidDroppable
  8. attr_accessible :lat, :lng, :payload, :user_id, :user, :expires_at
  9. acts_as_mappable
  10. json_serialize :payload
  11. belongs_to :user
  12. belongs_to :agent, :counter_cache => true, :touch => :last_event_at
  13. scope :recent, lambda { |timespan = 12.hours.ago|
  14. where("events.created_at > ?", timespan)
  15. }
  16. after_create :possibly_propagate
  17. # Emit this event again, as a new Event.
  18. def reemit!
  19. agent.create_event :payload => payload, :lat => lat, :lng => lng
  20. end
  21. # Look for Events whose `expires_at` is present and in the past. Remove those events and then update affected Agents'
  22. # `events_counts` cache columns. This method is called by bin/schedule.rb periodically.
  23. def self.cleanup_expired!
  24. affected_agents = Event.where("expires_at IS NOT NULL AND expires_at < ?", Time.now).group("agent_id").pluck(:agent_id)
  25. Event.where("expires_at IS NOT NULL AND expires_at < ?", Time.now).delete_all
  26. Agent.where(:id => affected_agents).update_all "events_count = (select count(*) from events where agent_id = agents.id)"
  27. end
  28. protected
  29. def possibly_propagate
  30. #immediately schedule agents that want immediate updates
  31. propagate_ids = agent.receivers.where(:propagate_immediately => true).pluck(:id)
  32. Agent.receive!(:only_receivers => propagate_ids) unless propagate_ids.empty?
  33. end
  34. end
  35. class EventDrop
  36. def initialize(object, locals = nil)
  37. locals ||= object.payload
  38. super
  39. end
  40. def each(&block)
  41. return to_enum(__method__) unless block
  42. @locals.each(&block)
  43. end
  44. def agent
  45. @object.agent
  46. end
  47. def created_at
  48. @object.created_at
  49. end
  50. end