attributes.rb 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. # Copyright (C) 2012-2022 Zammad Foundation, https://zammad-foundation.org/
  2. class Sequencer
  3. class Units < SimpleDelegator
  4. # Initializes the lifespan store for the attributes
  5. # of the given Units declarations.
  6. #
  7. # @param [Array<Hash{Symbol => Array<:Symbol>}>] declarations the list of Unit declarations.
  8. #
  9. # @example
  10. # declarations = [{uses: [:attribute1, ...], provides: [:result], ...}]
  11. # attributes = Sequencer::Units::Attributes(declarations)
  12. class Attributes < Delegator
  13. # Lists all `provides` declarations of the Units the instance was initialized with.
  14. #
  15. # @example
  16. # attributes.provided
  17. # # => [:result, ...]
  18. #
  19. # @return [Array<Symbol>] the list of all `provides` declarations
  20. def provided
  21. select do |_attribute, instance|
  22. instance.will_be_provided?
  23. end.keys
  24. end
  25. # Lists all `uses` declarations of the Units the instance was initialized with.
  26. #
  27. # @example
  28. # attributes.used
  29. # # => [:attribute1, ...]
  30. #
  31. # @return [Array<Symbol>] the list of all `uses` declarations
  32. def used
  33. select do |_attribute, instance|
  34. instance.will_be_used?
  35. end.keys
  36. end
  37. # Checks if the given attribute is known in the list of Unit declarations.
  38. #
  39. # @example
  40. # attributes.known?(:attribute2)
  41. # # => false
  42. #
  43. # @return [Boolean]
  44. def known?(attribute)
  45. key?(attribute)
  46. end
  47. def __getobj__
  48. @attributes
  49. end
  50. def __setobj__(declarations)
  51. @attributes ||= begin # rubocop:disable Naming/MemoizedInstanceVariableName
  52. attributes = Hash.new do |hash, key|
  53. hash[key] = Sequencer::Units::Attribute.new
  54. end
  55. attributes.tap do |result|
  56. declarations.each_with_index do |unit, index|
  57. unit[:uses].try(:each) do |attribute|
  58. result[attribute].to = index
  59. end
  60. unit[:provides].try(:each) do |attribute|
  61. next if result[attribute].will_be_provided?
  62. result[attribute].from = index
  63. end
  64. unit[:optional].try(:each) do |attribute|
  65. result[attribute].optional = index
  66. end
  67. end
  68. end
  69. end
  70. end
  71. end
  72. end
  73. end