Class: Lutaml::Model::Store

Inherits:
Object
  • Object
show all
Defined in:
lib/lutaml/model/store.rb

Constant Summary collapse

COMPACTION_THRESHOLD =

Compact dead WeakRef shells after this many entries per class bucket.

1000

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeStore

Returns a new instance of Store.



37
38
39
40
41
42
# File 'lib/lutaml/model/store.rb', line 37

def initialize
  @store = ::Hash.new { |hash, key| hash[key] = [] }
  # Lazy index: built on first resolve for a given (class, key) pair.
  # Key: [class_name, reference_method] → { value => WeakRef(object) }
  @index = {}
end

Class Method Details

.clearObject



28
29
30
# File 'lib/lutaml/model/store.rb', line 28

def clear
  instance.clear
end

.instanceObject



12
13
14
# File 'lib/lutaml/model/store.rb', line 12

def instance
  @instance ||= new
end

.register(object) ⇒ Object



20
21
22
# File 'lib/lutaml/model/store.rb', line 20

def register(object)
  instance.register(object)
end

.reset!Object



16
17
18
# File 'lib/lutaml/model/store.rb', line 16

def reset!
  @instance = new
end

.resolve(model_class, reference_key, reference_value) ⇒ Object



24
25
26
# File 'lib/lutaml/model/store.rb', line 24

def resolve(model_class, reference_key, reference_value)
  instance.resolve(model_class, reference_key, reference_value)
end

.storeObject



32
33
34
# File 'lib/lutaml/model/store.rb', line 32

def store
  instance.store
end

Instance Method Details

#clearObject



75
76
77
78
# File 'lib/lutaml/model/store.rb', line 75

def clear
  @store = ::Hash.new { |hash, key| hash[key] = [] }
  @index = {}
end

#register(object) ⇒ Object



44
45
46
47
48
49
50
51
52
# File 'lib/lutaml/model/store.rb', line 44

def register(object)
  model_key = object.class.to_s
  refs = @store[model_key]
  refs << WeakRef.new(object)

  compact_if_needed(refs)

  update_existing_indices(object, model_key)
end

#resolve(model_class, reference_key, reference_value) ⇒ Object



54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/lutaml/model/store.rb', line 54

def resolve(model_class, reference_key, reference_value)
  model_key = model_class.to_s
  index_key = [model_key, reference_key]

  # Build index lazily on first resolve for this (class, key) pair
  unless @index.key?(index_key)
    ensure_index(index_key, model_key,
                 reference_key)
  end

  # O(1) indexed lookup
  entry = @index[index_key][reference_value]
  return nil unless entry

  begin
    entry.__getobj__ if entry.weakref_alive?
  rescue WeakRef::RefError
    nil
  end
end

#storeObject



80
81
82
83
84
85
86
87
88
# File 'lib/lutaml/model/store.rb', line 80

def store
  @store.transform_values do |refs|
    refs.each_with_object([]) do |ref, alive|
      alive << ref.__getobj__ if ref.weakref_alive?
    rescue WeakRef::RefError
      nil
    end
  end
end