agents_exporter.rb 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. class AgentsExporter
  2. attr_accessor :options
  3. def initialize(options)
  4. self.options = options
  5. end
  6. # Filename should have no commas or special characters to support Content-Disposition on older browsers.
  7. def filename
  8. ((options[:name] || '').downcase.gsub(/[^a-z0-9_-]/, '-').gsub(/-+/, '-').gsub(/^-|-$/, '').presence || 'exported-agents') + ".json"
  9. end
  10. def as_json(opts = {})
  11. {
  12. :name => options[:name].presence || 'No name provided',
  13. :description => options[:description].presence || 'No description provided',
  14. :source_url => options[:source_url],
  15. :guid => options[:guid],
  16. :exported_at => Time.now.utc.iso8601,
  17. :agents => agents.map { |agent| agent_as_json(agent) },
  18. :links => links
  19. }
  20. end
  21. def agents
  22. options[:agents].to_a
  23. end
  24. def links
  25. agent_ids = agents.map(&:id)
  26. contained_links = agents.map.with_index do |agent, index|
  27. agent.links_as_source.where(:receiver_id => agent_ids).map do |link|
  28. { :source => index, :receiver => agent_ids.index(link.receiver_id) }
  29. end
  30. end
  31. contained_links.flatten.compact
  32. end
  33. def agent_as_json(agent)
  34. {
  35. :type => agent.type,
  36. :name => agent.name,
  37. :disabled => agent.disabled,
  38. :guid => agent.guid,
  39. :options => agent.options
  40. }.tap do |options|
  41. options[:schedule] = agent.schedule if agent.can_be_scheduled?
  42. options[:keep_events_for] = agent.keep_events_for if agent.can_create_events?
  43. options[:propagate_immediately] = agent.propagate_immediately if agent.can_receive_events?
  44. end
  45. end
  46. end