check.rb 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. module Blazer
  2. class Check < ActiveRecord::Base
  3. belongs_to :creator, Blazer::BELONGS_TO_OPTIONAL.merge(class_name: Blazer.user_class.to_s) if Blazer.user_class
  4. belongs_to :query
  5. validates :query_id, presence: true
  6. before_validation :set_state
  7. def set_state
  8. self.state ||= "new"
  9. end
  10. def split_emails
  11. emails.to_s.downcase.split(",").map(&:strip)
  12. end
  13. def update_state(result)
  14. check_type =
  15. if respond_to?(:check_type)
  16. self.check_type
  17. elsif respond_to?(:invert)
  18. invert ? "missing_data" : "bad_data"
  19. else
  20. "bad_data"
  21. end
  22. message = result.error
  23. self.state =
  24. if result.timed_out?
  25. "timed out"
  26. elsif result.error
  27. "error"
  28. elsif check_type == "anomaly"
  29. anomaly, message = result.detect_anomaly
  30. if anomaly.nil?
  31. "error"
  32. elsif anomaly
  33. "failing"
  34. else
  35. "passing"
  36. end
  37. elsif result.rows.any?
  38. check_type == "missing_data" ? "passing" : "failing"
  39. else
  40. check_type == "missing_data" ? "failing" : "passing"
  41. end
  42. self.last_run_at = Time.now if respond_to?(:last_run_at=)
  43. self.message = message if respond_to?(:message=)
  44. if respond_to?(:timeouts=)
  45. if result.timed_out?
  46. self.timeouts += 1
  47. self.state = "disabled" if timeouts >= 3
  48. else
  49. self.timeouts = 0
  50. end
  51. end
  52. # do not notify on creation, except when not passing
  53. if (state_was != "new" || state != "passing") && state != state_was && emails.present?
  54. Blazer::CheckMailer.state_change(self, state, state_was, result.rows.size, message).deliver_later
  55. end
  56. save! if changed?
  57. end
  58. end
  59. end