units.rb 1.6 KB

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