sequencer.rb 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. require_dependency 'mixin/rails_logger'
  2. require_dependency 'mixin/start_finish_logger'
  3. class Sequencer
  4. include ::Mixin::RailsLogger
  5. include ::Mixin::StartFinishLogger
  6. attr_reader :sequence
  7. # Convenience wrapper for instant processing with the given attributes.
  8. #
  9. # @example
  10. # Sequencer.process('Example::Sequence')
  11. #
  12. # @example
  13. # Sequencer.process('Example::Sequence',
  14. # parameters: {
  15. # some: 'value',
  16. # },
  17. # expecting: [:result, :answer]
  18. # )
  19. #
  20. # @return [Hash{Symbol => Object}] the final result state attributes and values
  21. def self.process(sequence, *args)
  22. new(sequence, *args).process
  23. end
  24. # Initializes a new Sequencer instance for the given Sequence with parameters and expecting result.
  25. #
  26. # @example
  27. # Sequencer.new('Example::Sequence')
  28. #
  29. # @example
  30. # Sequencer.new('Example::Sequence',
  31. # parameters: {
  32. # some: 'value',
  33. # },
  34. # expecting: [:result, :answer]
  35. # )
  36. def initialize(sequence, parameters: {}, expecting: nil)
  37. @sequence = Sequencer::Sequence.constantize(sequence)
  38. @parameters = parameters
  39. @expecting = expecting
  40. # fall back to sequence default expecting if no explicit
  41. # expecting was given for this sequence
  42. return if !@expecting.nil?
  43. @expecting = @sequence.expecting
  44. end
  45. # Processes the Sequence the instance was initialized with.
  46. #
  47. # @example
  48. # sequence.process
  49. #
  50. # @return [Hash{Symbol => Object}] the final result state attributes and values
  51. def process
  52. log_start_finish(:info, "Sequence '#{sequence.name}'") do
  53. sequence.units.each_with_index do |unit, index|
  54. state.process do
  55. log_start_finish(:info, "Sequence '#{sequence.name}' Unit '#{unit.name}' (index: #{index})") do
  56. unit.process(state)
  57. end
  58. end
  59. end
  60. end
  61. state.to_h.tap do |result|
  62. logger.debug { "Returning Sequence '#{sequence.name}' result: #{result.inspect}" }
  63. end
  64. end
  65. private
  66. def state
  67. @state ||= Sequencer::State.new(sequence,
  68. parameters: @parameters,
  69. expecting: @expecting)
  70. end
  71. end