dry_runnable.rb 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. module DryRunnable
  2. extend ActiveSupport::Concern
  3. def dry_run!(event = nil)
  4. @dry_run = true
  5. log = StringIO.new
  6. @dry_run_logger = Logger.new(log)
  7. @dry_run_results = {
  8. events: [],
  9. }
  10. begin
  11. raise "#{short_type} does not support dry-run" unless can_dry_run?
  12. readonly!
  13. if event
  14. raise "This agent cannot receive an event!" unless can_receive_events?
  15. receive([event])
  16. else
  17. check
  18. end
  19. rescue => e
  20. error "Exception during dry-run. #{e.message}: #{e.backtrace.join("\n")}"
  21. end
  22. @dry_run_results.update(
  23. memory: memory,
  24. log: log.string,
  25. )
  26. ensure
  27. @dry_run = false
  28. end
  29. def dry_run?
  30. !!@dry_run
  31. end
  32. included do
  33. prepend Wrapper
  34. end
  35. module Wrapper
  36. attr_accessor :results
  37. def logger
  38. return super unless dry_run?
  39. @dry_run_logger
  40. end
  41. def save(options = {})
  42. return super unless dry_run?
  43. perform_validations(options)
  44. end
  45. def save!(options = {})
  46. return super unless dry_run?
  47. save(options) or raise_record_invalid
  48. end
  49. def log(message, options = {})
  50. return super unless dry_run?
  51. case options[:level] || 3
  52. when 0..2
  53. sev = Logger::DEBUG
  54. when 3
  55. sev = Logger::INFO
  56. else
  57. sev = Logger::ERROR
  58. end
  59. logger.log(sev, message)
  60. end
  61. def create_event(event)
  62. return super unless dry_run?
  63. if can_create_events?
  64. event = build_event(event)
  65. @dry_run_results[:events] << event.payload
  66. event
  67. else
  68. error "This Agent cannot create events!"
  69. end
  70. end
  71. end
  72. end