Class: OsCtl::Lib::Index

Inherits:
Object
  • Object
show all
Defined in:
lib/libosctl/index.rb

Overview

Hash-based cache for collection lookups by key

Index is not thread-safe.

Instance Method Summary collapse

Constructor Details

#initialize {|obj| ... } ⇒ Index

Returns a new instance of Index

Yield Parameters:

  • obj (Object)

    the indexed object

Yield Returns:

  • (String)

    key for the indexed object



8
9
10
11
# File 'lib/libosctl/index.rb', line 8

def initialize(&block)
  @block = block
  @index = {}
end

Instance Method Details

#<<(obj) ⇒ Object

Add object to the index

Parameters:

  • obj (Object)


15
16
17
18
# File 'lib/libosctl/index.rb', line 15

def <<(obj)
  @index[key(obj)] = obj
  self
end

#[](key) ⇒ Object

Lookup using string key

Parameters:

  • key (String)


22
23
24
# File 'lib/libosctl/index.rb', line 22

def [](key)
  @index[key]
end

#delete(obj) ⇒ Object

Delete object from the index

Parameters:

  • obj (Object)


28
29
30
# File 'lib/libosctl/index.rb', line 28

def delete(obj)
  @index.delete(key(obj))
end

#delete_key(key) ⇒ Object

Delete object from the index by key

Parameters:

  • key (String)


34
35
36
# File 'lib/libosctl/index.rb', line 34

def delete_key(key)
  @index.delete(key)
end

#empty?Boolean

Returns:

  • (Boolean)


38
39
40
# File 'lib/libosctl/index.rb', line 38

def empty?
  @index.empty?
end

#key(obj) ⇒ Object (protected)



43
44
45
# File 'lib/libosctl/index.rb', line 43

def key(obj)
  @block.call(obj)
end