fork download
  1. module Protocol
  2. class Packet
  3. class << self
  4. attr_reader :packet_id
  5. end
  6. end
  7.  
  8. class A < Packet
  9. @packet_id = 1
  10. end
  11.  
  12. class B < Packet
  13. @packet_id = 2
  14. end
  15.  
  16. class NotAPacket
  17. end
  18. end
  19.  
  20. mapping = Protocol.constants.each_with_object({}) do |constant_name, result|
  21. klass = Protocol.const_get(constant_name)
  22. next unless klass.is_a?(Class)
  23. next unless klass < Protocol::Packet
  24. result[klass.packet_id] = klass
  25. end
  26.  
  27. p mapping
  28. p mapping[1].new
  29.  
Success #stdin #stdout 0s 4716KB
stdin
Standard input is empty
stdout
{1=>Protocol::A, 2=>Protocol::B}
#<Protocol::A:0x9ce9e5c>