Class: Vli::Registry

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

Overview

Register components in a single location that can be queried.

This allows certain components (such as guest systems, configuration pieces, etc.) to be registered and queried.

Instance Method Summary collapse

Constructor Details

#initializeRegistry

Returns a new instance of Registry.



11
12
13
14
# File 'lib/vli/registry.rb', line 11

def initialize
  @actions = {}
  @results_cache = {}
end

Instance Method Details

#each(&block) ⇒ Object

Iterate over the keyspace.



40
41
42
43
44
# File 'lib/vli/registry.rb', line 40

def each(&block)
  @actions.each do |key, _|
    yield key, get(key)
  end
end

#get(key) ⇒ Object Also known as: []

Get an action by the given key.

This will evaluate the block given to ‘register` and return the resulting action stack.



32
33
34
35
36
# File 'lib/vli/registry.rb', line 32

def get(key)
  return nil if !@actions.has_key?(key)
  return @results_cache[key] if @results_cache.has_key?(key)
  @results_cache[key] = @actions[key].call
end

#register(key, value = nil, &block) ⇒ Object

Register a callable by key.

The callable should be given in a block which will be lazily evaluated when the action is needed.

If an action by the given name already exists then it will be overwritten.



23
24
25
26
# File 'lib/vli/registry.rb', line 23

def register(key, value=nil, &block)
  block = lambda { value } if value
  @actions[key] = block
end

#to_hashObject

Converts this registry to a hash



47
48
49
50
51
52
53
54
# File 'lib/vli/registry.rb', line 47

def to_hash
  result = {}
  self.each do |key, value|
    result[key] = value
  end

  result
end