Class: Tango::Resource::Cache

Inherits:
Object
  • Object
show all
Defined in:
lib/tango/resource/cache.rb

Overview

Key - value caching system for resources

Author:

  • Mckomo

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(buffer = nil) ⇒ Tango::Resources::Cache

Constructor of the Cache

Parameters:

  • buffer (Tango::Resources::Buffer) (defaults to: nil)


15
16
17
18
19
20
# File 'lib/tango/resource/cache.rb', line 15

def initialize( buffer = nil )
  # Set dependencies
  @buffer = buffer || Buffer.new
  # Container for resources cache
  @storage = {}   
end

Instance Attribute Details

#bufferObject (readonly)

Returns the value of attribute buffer.



9
10
11
# File 'lib/tango/resource/cache.rb', line 9

def buffer
  @buffer
end

Instance Method Details

#get(type, resource) ⇒ Object

Getter for the cache storage

Parameters:

  • type (Symbol)
  • key (String)

Returns:

  • (Object)

Raises:

  • (ArgumentError)


80
81
82
83
# File 'lib/tango/resource/cache.rb', line 80

def get( type, resource )
  raise ArgumentError, "Trying to get resource with unregistered type" unless @storage.keys.include?( type )
  @storage[type][resource.cache_key]
end

#load(type, resource) ⇒ Object

Get a cached resource or use given block to obtain resource and return it

Parameters:

  • type (Symbol)
  • resource (Object)

Returns:

  • (Object)


43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/tango/resource/cache.rb', line 43

def load( type, resource )
  
  # Get resource from cache
  cached_resource = get( type, resource )


  unless cached_resource
    
    raise ArgumentError, "No resource callback given" unless block_given?
    # If not found, execute yield to receive transformed resource
    cached_resource = yield( resource )
    # Cache new resource
    set( type, cached_resource )
    # Fill buffer with newly cached resource
    @buffer.fill( type, cached_resource )
    
  end
  
  cached_resource
  
end

#register(type, &release_callback) ⇒ Tango::Resource::Cache

Register new type of resource to be cached

Parameters:

  • type (Symbol)
  • release_callback (Proc)

Returns:



27
28
29
30
31
32
33
34
35
36
# File 'lib/tango/resource/cache.rb', line 27

def register( type, &release_callback  )
  
  # Create container for cache of new resource 
  @storage[type] = {}
  # Also register new type with buffer
  @buffer.register( type, &release_callback )
  
  self
  
end

#set(type, resource) ⇒ Object

Setter for the cache storage

Parameters:

  • type (Symbol)
  • resource (Object)

Returns:

  • (Object)

Raises:

  • (ArgumentError)


70
71
72
73
# File 'lib/tango/resource/cache.rb', line 70

def set( type, resource )
  raise ArgumentError, "Trying to set resource with unregistered type" unless @storage.keys.include?( type )
  @storage[type][resource.cache_key] = resource
end