Class: PEROBS::ClassMap
- Inherits:
-
Object
- Object
- PEROBS::ClassMap
- Defined in:
- lib/perobs/ClassMap.rb
Overview
PEROBS will usually store objects with a relatively small number of classes. Rather than storing the class name with each object, we map the class name to a numerical ID that represents the class in the store. This class handles the mapping and can convert class names into IDs and vice versa.
Instance Method Summary collapse
-
#class_to_id(klass) ⇒ Integer
Get the ID for a given class.
-
#id_to_class(id) ⇒ String
Get the klass for a given ID.
-
#initialize(db) ⇒ ClassMap
constructor
Create a ClassMap object for a given data base.
-
#keep(classes) ⇒ Object
Delete all classes unless they are contained in classes.
-
#rename(rename_map) ⇒ Object
Rename a set of classes to new names.
Constructor Details
#initialize(db) ⇒ ClassMap
Create a ClassMap object for a given data base.
41 42 43 44 45 46 |
# File 'lib/perobs/ClassMap.rb', line 41 def initialize(db) @db = db @by_class = {} @by_id = [] read_map end |
Instance Method Details
#class_to_id(klass) ⇒ Integer
Get the ID for a given class.
52 53 54 |
# File 'lib/perobs/ClassMap.rb', line 52 def class_to_id(klass) @by_class[klass] || new_id(klass) end |
#id_to_class(id) ⇒ String
Get the klass for a given ID.
59 60 61 |
# File 'lib/perobs/ClassMap.rb', line 59 def id_to_class(id) @by_id[id] end |
#keep(classes) ⇒ Object
Delete all classes unless they are contained in classes.
83 84 85 86 87 88 89 90 91 92 |
# File 'lib/perobs/ClassMap.rb', line 83 def keep(classes) @by_id.each.with_index do |klass, id| unless classes.include?(klass) # Delete the class from the @by_id list by setting the entry to nil. @by_id[id] = nil # Delete the corresponding @by_class entry as well. @by_class.delete(klass) end end end |
#rename(rename_map) ⇒ Object
Rename a set of classes to new names.
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 |
# File 'lib/perobs/ClassMap.rb', line 65 def rename(rename_map) @by_id.each.with_index do |klass, id| # Some entries can be nil. Ignore them. next unless klass if (new_name = rename_map[klass]) # We have a rename request. Update the current @by_id entry. @by_id[id] = new_name # Remove the old class name from @by_class hash. @by_class.delete(klass) # Insert the new one with the current ID. @by_class[new_name] = id end end end |