Class: Multiton::InstanceBox

Inherits:
Object
  • Object
show all
Defined in:
lib/multiton/instance_box.rb

Overview

InstanceBox is a thread safe container for storing and retrieving multiton instances.

Instance Method Summary collapse

Constructor Details

#initializeInstanceBox

call-seq:

new => new_instance

Returns a new InstanceBox instance.



13
14
15
16
17
# File 'lib/multiton/instance_box.rb', line 13

def initialize
  self.hash = {}
  self.sync = Sync.new
  self
end

Instance Method Details

#get(key) ⇒ Object

call-seq:

get(key) => instance

Returns the instance associated with key. If key does not exist it returns nil.



24
25
26
# File 'lib/multiton/instance_box.rb', line 24

def get(key)
  sync.synchronize(:SH) { hash[key] }
end

#key(instance) ⇒ Object

call-seq:

key(instance) => key

Returns the multiton key associated with instance. If instance does not exist it returns nil.



33
34
35
# File 'lib/multiton/instance_box.rb', line 33

def key(instance)
  sync.synchronize(:SH) { Utils.hash_key(hash, instance) }
end

#store(key, instance) ⇒ Object

call-seq:

store(key, instance) => instance

Stores instance indexed by key.

Returns instance.



44
45
46
# File 'lib/multiton/instance_box.rb', line 44

def store(key, instance)
  sync.synchronize(:EX) { hash[key] ||= instance }
end