units.rb 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. # Copyright (C) 2012-2022 Zammad Foundation, https://zammad-foundation.org/
  2. class Sequencer
  3. class Units < SimpleDelegator
  4. include ::Enumerable
  5. # Initializes a new Sequencer::Units instance with the given Units Array.
  6. #
  7. # @param [*Array<String>] *units a list of Units with or without the Sequencer::Unit prefix.
  8. #
  9. # @example
  10. # Sequencer::Units.new('Example::Unit', 'Sequencer::Unit::Second::Unit')
  11. def initialize(*units)
  12. super(units)
  13. end
  14. # Required #each implementation for ::Enumerable functionality. Constantizes
  15. # the list of units given when initialized.
  16. #
  17. # @example
  18. # units.each do |unit|
  19. # unit.process(sequencer)
  20. # end
  21. #
  22. # @return [nil]
  23. def each
  24. __getobj__.each do |unit|
  25. yield constantize(unit)
  26. end
  27. end
  28. # Provides an Array of :uses, :provides and :optional declarations for each Unit.
  29. #
  30. # @example
  31. # units.declarations
  32. # #=> [{uses: [:question], provides: [:answer], optional: [:facts], ...}]
  33. #
  34. # @return [Array<Hash{Symbol => Array<Symbol>}>] the declarations of the Units
  35. def declarations
  36. collect do |unit|
  37. {
  38. uses: unit.uses,
  39. provides: unit.provides,
  40. optional: unit.optional,
  41. }
  42. end
  43. end
  44. # Enables the access to an Unit class via index.
  45. #
  46. # @param [Integer] index the index for the requested Unit class.
  47. #
  48. # @example
  49. # units[1]
  50. # #=> Sequencer::Unit::Example
  51. #
  52. # @return [Object] the Unit class for the requested index
  53. def [](index)
  54. constantize(__getobj__[index])
  55. end
  56. private
  57. def constantize(unit)
  58. Sequencer::Unit.constantize(unit)
  59. end
  60. end
  61. end