unit.rb 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. require 'sequencer/mixin/prefixed_constantize'
  2. class Sequencer
  3. class Unit
  4. include ::Mixin::RequiredSubPaths
  5. extend ::Sequencer::Mixin::PrefixedConstantize
  6. PREFIX = 'Sequencer::Unit::'.freeze
  7. # Convenience wrapper for processing a single Unit.
  8. #
  9. # ATTENTION: This should only be used for development, testing or debugging purposes.
  10. # There might be a check in the future to prevent using this method in other scopes.
  11. #
  12. # @see #initialize
  13. # @see #process
  14. def self.process(unit, parameters, &block)
  15. new(unit).process(parameters, &block)
  16. end
  17. # Initializes a new Sequencer::Unit for processing it.
  18. #
  19. # ATTENTION: This should only be used for development, testing or debugging purposes.
  20. # There might be a check in the future to prevent using this method in other scopes.
  21. #
  22. # @param [String] unit the name String for the Unit that should get processed
  23. def initialize(unit)
  24. @unit = self.class.constantize(unit)
  25. end
  26. # Processes the Sequencer::Unit that the instance was initialized with.
  27. #
  28. # ATTENTION: This should only be used for development, testing or debugging purposes.
  29. # There might be a check in the future to prevent using this method in other scopes.
  30. #
  31. # @param [Hash{Symbol => Object}] parameters the parameters for initializing the Sequencer::State
  32. # @yield [instance] optional block to access the Unit instance
  33. # @yieldparam instance [Object] the Unit instance for e.g. adding expectations
  34. def process(parameters)
  35. @parameters = parameters
  36. instance = @unit.new(state)
  37. # yield instance to apply expectations
  38. yield instance if block_given?
  39. state.process do
  40. instance.process
  41. end
  42. state.to_h
  43. end
  44. private
  45. def state
  46. @state ||= begin
  47. units = Sequencer::Units.new(
  48. @unit.name
  49. )
  50. sequence = Sequencer::Sequence.new(
  51. units: units,
  52. expecting: @unit.provides,
  53. )
  54. Sequencer::State.new(sequence,
  55. parameters: @parameters)
  56. end
  57. end
  58. end
  59. end