Class: BlockCache

Inherits:
Object show all
Defined in:
lib/block_cache.rb

Overview

a ruby class contains a list of objects

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(cache = []) ⇒ BlockCache

Returns a new instance of BlockCache.



10
11
12
# File 'lib/block_cache.rb', line 10

def initialize(cache = [])
  @cache = cache
end

Instance Attribute Details

#cacheObject

Returns the value of attribute cache.



8
9
10
# File 'lib/block_cache.rb', line 8

def cache
  @cache
end

Instance Method Details

#add(obj) ⇒ Object

Add a new object to the cache

Raises:

  • (ArgumentError)


38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/block_cache.rb', line 38

def add(obj)
  raise ArgumentError,
        'Object must respond to id method' unless obj.respond_to?(:id)

  # Replace existing object with same id
  if (existing = find_by_id(obj.id))
    @cache[@cache.index(existing)] = obj
  else
    @cache << obj
  end
  obj
end

#clearObject

Clear the entire cache



57
58
59
# File 'lib/block_cache.rb', line 57

def clear
  @cache = []
end

#find_by_id(id) ⇒ Object

Find an object by id



15
16
17
# File 'lib/block_cache.rb', line 15

def find_by_id(id)
  @cache.find { |obj| obj.id == id }
end

#get_or_create(id, new_obj_proc = nil) ⇒ Object

Get an existing object by id or create a new one



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/block_cache.rb', line 20

def get_or_create(id, new_obj_proc = nil)
  obj = find_by_id(id)
  return obj if obj

  # Create a new object if not found
  if block_given?
    obj = yield(id)
  elsif new_obj_proc
    obj = new_obj_proc.call(id)
  else
    raise ArgumentError, 'Block or proc required to create new object'
  end

  @cache << obj
  obj
end

#remove(id) ⇒ Object

Remove an object from the cache by id



52
53
54
# File 'lib/block_cache.rb', line 52

def remove(id)
  @cache.delete_if { |obj| obj.id == id }
end

#sizeObject

Get the size of the cache



62
63
64
# File 'lib/block_cache.rb', line 62

def size
  @cache.size
end