Ruby Resource Management

A resource manager for the lovely language Ruby. Since it has a garbage collector built into it the manager don't need to do much. So it acts more like a common place to collect handles to external files. Since the resources are allocated in Ruby it is fully legal to acquire a reference to a resource and afterward delete it from the manager. It is also supported to use a different path than the symbol given using the ResourceManager#load method.

The code has been tested on Ruby-1.9.2p0

Simple Example

require 'sfml/all'
require './ResourceManager.rb'
 
manager = ResourceManager.new( SFML::Image, :loadFromFile )
instance = manager.load( :anImage, "path/to/image" )
if( instance == manager.get( :anImage ) )
  puts "The same!"
end

Even though I use the load method here, you can use directly the get method. If the resource doesn't exist, then it will use the given symbol as the path to the resource.

Source

class ResourceManager
 
  def get( aSymbol )
    instance = @resources[  aSymbol ]
    if instance.nil?
      instance = load( aSymbol, aSymbol )
    end
    return instance
  end
 
  def load( aSymbol, aPath )
    instance = load_resource( aPath )
    @resources[ aSymbol ] = instance
  end
 
  def delete( aSymbol )
    @resources.delete( aSymbol )
  end
 
  def delete_all( aSymbol )
    @resources.clear()
    nil
  end
 
  def size()
    return @resources.size
  end
 
protected
  def initialize( aClass, aLoadMethod )
    @class = aClass
    @loadMethod = aLoadMethod
    @resources = {}
  end
 
  def load_resource( aPath )
    instance = @class.new
    if( instance.send( @loadMethod, aPath ) == false )
      raise RuntimeError, "Failed to load #{ @class.to_s } resource #{ aPath }"
    end
    return instance
  end
end
 
en/sources/ruby_resource_manager.txt · Last modified: 2011/02/05 18:26 by Groogy
 
Recent changes RSS feed Creative Commons License Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki