units.rb 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. require 'sequencer/units/attribute'
  2. require 'sequencer/units/attributes'
  3. class Sequencer
  4. class Units < SimpleDelegator
  5. include ::Enumerable
  6. # Initializes a new Sequencer::Units instance with the given Units Array.
  7. #
  8. # @param [*Array<String>] *units a list of Units with or without the Sequencer::Unit prefix.
  9. #
  10. # @example
  11. # Sequencer::Units.new('Example::Unit', 'Sequencer::Unit::Second::Unit')
  12. def initialize(*units)
  13. super(units)
  14. end
  15. # Required #each implementation for ::Enumerable functionality. Constantizes
  16. # the list of units given when initialized.
  17. #
  18. # @example
  19. # units.each do |unit|
  20. # unit.process(sequencer)
  21. # end
  22. #
  23. # @return [nil]
  24. def each
  25. __getobj__.each do |unit|
  26. yield constantize(unit)
  27. end
  28. end
  29. # Provides an Array of :uses and :provides declarations for each Unit.
  30. #
  31. # @example
  32. # units.declarations
  33. # #=> [{uses: [:question], provides: [:answer], ...}]
  34. #
  35. # @return [Array<Hash{Symbol => Array<Symbol>}>] the declarations of the Units
  36. def declarations
  37. collect do |unit|
  38. {
  39. uses: unit.uses,
  40. provides: unit.provides,
  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