units.rb 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. require_dependency 'sequencer/units/attribute'
  2. require_dependency '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, :provides and :optional declarations for each Unit.
  30. #
  31. # @example
  32. # units.declarations
  33. # #=> [{uses: [:question], provides: [:answer], optional: [:facts], ...}]
  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. optional: unit.optional,
  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(__getobj__[index])
  56. end
  57. private
  58. def constantize(unit)
  59. Sequencer::Unit.constantize(unit)
  60. end
  61. end
  62. end