registry.rb 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. # The registry module can be extended into a class to enable
  2. # by name and by id registry storage and lookup
  3. module Registry
  4. # Sets up the registry
  5. def prepare_registry
  6. @registry_by_id ||= {}
  7. @registry_by_name ||= {}
  8. end
  9. def registry_by_name
  10. prepare_registry
  11. return @registry_by_name
  12. end
  13. # Gets the id and name for the object for use with the registry
  14. def get_registry_id_and_name(obj, id = nil, name = nil)
  15. id = obj.id if obj.respond_to? :id
  16. name = obj.name if obj.respond_to? :name
  17. name = (name ? name.to_s.to_sym : id.to_s.to_sym)
  18. return id, name
  19. end
  20. # Registers the object with the given numeric ID and name
  21. # The obj should respond to :name and :id
  22. def register(obj, id = nil, name = nil)
  23. prepare_registry
  24. id, name = get_registry_id_and_name(obj, id, name)
  25. @registry_by_id[id] = obj
  26. @registry_by_name[name.to_sym] = obj
  27. end
  28. # Unregisters the object
  29. def unregister(obj, id = nil, name = nil)
  30. prepare_registry
  31. id, name = get_registry_id_and_name(obj, id, name)
  32. @registry_by_id[id] = nil
  33. @registry_by_name[name.to_sym] = nil
  34. end
  35. # Looks up an item in the registry by name or by id.
  36. # If thing responds to :to_sym it's looked up as a name,
  37. # otherwise it's looked up by numerical
  38. def [](name_or_id)
  39. prepare_registry
  40. if name_or_id.respond_to? :to_sym
  41. return @registry_by_name[name_or_id.to_sym]
  42. else
  43. return @registry_by_id[name_or_id]
  44. end
  45. end
  46. # Other way to say self[]
  47. def lookup(name_or_id)
  48. return self[name_or_id]
  49. end
  50. # Calls a callback for each registry item with name, item
  51. def registry_each_name
  52. @registry_by_name.each do | n, e |
  53. yield n, e
  54. end
  55. end
  56. # Calls a callback for each registry item with id, item
  57. def registry_each_id
  58. @registry_by_id.each do | id, e |
  59. yield id, e
  60. end
  61. end
  62. end