dry_runnable.rb 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. module DryRunnable
  2. def dry_run!
  3. readonly!
  4. class << self
  5. prepend Sandbox
  6. end
  7. log = StringIO.new
  8. @dry_run_logger = Logger.new(log)
  9. @dry_run_results = {
  10. events: [],
  11. }
  12. begin
  13. raise "#{short_type} does not support dry-run" unless can_dry_run?
  14. check
  15. rescue => e
  16. error "Exception during dry-run. #{e.message}: #{e.backtrace.join("\n")}"
  17. end
  18. @dry_run_results.update(
  19. memory: memory,
  20. log: log.string,
  21. )
  22. end
  23. def dry_run?
  24. is_a? Sandbox
  25. end
  26. module Sandbox
  27. attr_accessor :results
  28. def logger
  29. @dry_run_logger
  30. end
  31. def save
  32. valid?
  33. end
  34. def save!
  35. save or raise ActiveRecord::RecordNotSaved
  36. end
  37. def log(message, options = {})
  38. case options[:level] || 3
  39. when 0..2
  40. sev = Logger::DEBUG
  41. when 3
  42. sev = Logger::INFO
  43. else
  44. sev = Logger::ERROR
  45. end
  46. logger.log(sev, message)
  47. end
  48. def create_event(event_hash)
  49. if can_create_events?
  50. @dry_run_results[:events] << event_hash[:payload]
  51. events.build({ user: user, expires_at: new_event_expiration_date }.merge(event_hash))
  52. else
  53. error "This Agent cannot create events!"
  54. end
  55. end
  56. end
  57. end