prefixed_constantize.rb 1.4 KB

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