scenario.rb 1.4KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. class Scenario < ActiveRecord::Base
  2. include HasGuid
  3. attr_accessible :name, :agent_ids, :description, :public, :source_url,
  4. :tag_fg_color, :tag_bg_color, :icon
  5. belongs_to :user, :counter_cache => :scenario_count, :inverse_of => :scenarios
  6. has_many :scenario_memberships, :dependent => :destroy, :inverse_of => :scenario
  7. has_many :agents, :through => :scenario_memberships, :inverse_of => :scenarios
  8. validates_presence_of :name, :user
  9. validates_format_of :tag_fg_color, :tag_bg_color,
  10. # Regex adapted from: http://stackoverflow.com/a/1636354/3130625
  11. :with => /\A#(?:[0-9a-fA-F]{3}){1,2}\z/, :allow_nil => true,
  12. :message => "must be a valid hex color."
  13. validate :agents_are_owned
  14. def destroy_with_mode(mode)
  15. case mode
  16. when 'all_agents'
  17. Agent.destroy(agents.pluck(:id))
  18. when 'unique_agents'
  19. Agent.destroy(unique_agent_ids)
  20. end
  21. destroy
  22. end
  23. def self.icons
  24. @icons ||= begin
  25. YAML.load_file(Rails.root.join('config/icons.yml'))
  26. end
  27. end
  28. private
  29. def unique_agent_ids
  30. agents.joins(:scenario_memberships)
  31. .group('scenario_memberships.agent_id')
  32. .having('count(scenario_memberships.agent_id) = 1')
  33. .pluck('scenario_memberships.agent_id')
  34. end
  35. def agents_are_owned
  36. unless agents.all? { |s| s.user == user }
  37. errors.add(:agents, 'must be owned by you')
  38. end
  39. end
  40. end