Class: DispatchPolicy::Registry

Inherits:
Object
  • Object
show all
Defined in:
lib/dispatch_policy/registry.rb

Instance Method Summary collapse

Constructor Details

#initializeRegistry

Returns a new instance of Registry.



5
6
7
8
# File 'lib/dispatch_policy/registry.rb', line 5

def initialize
  @mutex    = Mutex.new
  @policies = {}
end

Instance Method Details

#[](name) ⇒ Object



26
27
28
# File 'lib/dispatch_policy/registry.rb', line 26

def [](name)
  fetch(name)
end

#clearObject



46
47
48
# File 'lib/dispatch_policy/registry.rb', line 46

def clear
  @mutex.synchronize { @policies.clear }
end

#each(&block) ⇒ Object



34
35
36
37
38
39
40
# File 'lib/dispatch_policy/registry.rb', line 34

def each(&block)
  # Snapshot under the lock, then iterate outside it: the block may run
  # arbitrary code (and Mutex isn't reentrant), so we must not hold the
  # lock while yielding.
  snapshot = @mutex.synchronize { @policies.values.map { |e| e[:policy] } }
  snapshot.each(&block)
end

#fetch(name) ⇒ Object



21
22
23
24
# File 'lib/dispatch_policy/registry.rb', line 21

def fetch(name)
  entry = @mutex.synchronize { @policies[name.to_s] }
  entry && entry[:policy]
end

#namesObject



30
31
32
# File 'lib/dispatch_policy/registry.rb', line 30

def names
  @mutex.synchronize { @policies.keys }
end

#register(policy, owner: nil) ⇒ Object



10
11
12
13
14
15
16
17
18
19
# File 'lib/dispatch_policy/registry.rb', line 10

def register(policy, owner: nil)
  @mutex.synchronize do
    existing = @policies[policy.name]
    if existing && existing[:owner] != owner
      raise PolicyAlreadyRegistered, "policy #{policy.name.inspect} already registered for #{existing[:owner]}"
    end
    @policies[policy.name] = { policy: policy, owner: owner }
  end
  policy
end

#sizeObject



42
43
44
# File 'lib/dispatch_policy/registry.rb', line 42

def size
  @mutex.synchronize { @policies.size }
end