prefixed_constantize.rb 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. # Classes that extend this module need a PREFIX constant.
  3. module Sequencer::Mixin::PrefixedConstantize
  4. # Returns the class for a given name String independend of the prefix.
  5. #
  6. # @param [String] sequence the name String for the requested class
  7. #
  8. # @example
  9. # Sequencer::Sequence.constantize('ExampleSequence')
  10. # #=> Sequencer::Sequence::ExampleSequence
  11. #
  12. # @example
  13. # Sequencer::Unit.constantize('Sequencer::Unit::Example::Unit')
  14. # #=> Sequencer::Unit::Example::Unit
  15. #
  16. # @return [Object] the class for the given String
  17. def constantize(name_string)
  18. namespace(name_string).constantize
  19. end
  20. # Returns the complete class namespace for a given name String
  21. # independend of the prefix.
  22. #
  23. # @param [String] sequence the name String for the requested class namespace
  24. #
  25. # @example
  26. # Sequencer::Sequence.namespace('ExampleSequence')
  27. # #=> 'Sequencer::Sequence::ExampleSequence'
  28. #
  29. # @example
  30. # Sequencer::Unit.namespace('Sequencer::Unit::Example::Unit')
  31. # #=> 'Sequencer::Unit::Example::Unit'
  32. #
  33. # @return [String] the class namespace for the given String
  34. def namespace(name_string)
  35. prefix = const_get(:PREFIX)
  36. return name_string if name_string.start_with?(prefix)
  37. "#{prefix}#{name_string}"
  38. end
  39. end