class Tango::Resource::Cache

Key - value caching system for resources

@author Mckomo

Attributes

buffer[R]

Public Class Methods

new( buffer = nil ) click to toggle source

Constructor of the Cache

@param buffer [Tango::Resources::Buffer] @return [Tango::Resources::Cache]

# File lib/tango/resource/cache.rb, line 15
def initialize( buffer = nil )
  # Set dependencies
  @buffer = buffer || Buffer.new
  # Container for resources cache
  @storage = {}   
end

Public Instance Methods

get( type, resource ) click to toggle source

Getter for the cache storage

@param type [Symbol] @param key [String] @return [Object]

# 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 ) { |resource| ... } click to toggle source

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

@param type [Symbol] @param resource [Object] @return [Object]

# 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 ) click to toggle source

Register new type of resource to be cached

@param type [Symbol] @param release_callback [Proc] @return [Tango::Resource::Cache]

# 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 ) click to toggle source

Setter for the cache storage

@param type [Symbol] @param resource [Object] @return [Object]

# 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