Class: PEROBS::ClassMap

Inherits:
Object
  • Object
show all
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

Constructor Details

#initialize(db) ⇒ ClassMap

Create a ClassMap object for a given data base.

Parameters:



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.

Parameters:

  • klass (String)

    Class

Returns:

  • (Integer)

    ID. If klass is not yet known a new ID will be allocated.



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.

Parameters:

  • id (Integer)

Returns:

  • (String)

    String version of the class



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.

Parameters:

  • classes (Array of String)

    List of the class names



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.

Parameters:

  • rename_map (Hash)

    Hash that maps old names 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