Methods

Class/Module Index [+]

Quicksearch

Rubygame::NamedResource

NamedResource is a mix-in module to implement a globally-available resource table, a @name variable and accessors, and a system for automatically loading resources when they are first needed.

This module is used for Rubygame::Music, Rubygame::Sound, and Rubygame::Surface. You can use it in your own classes this way:

  1. Do ‘include Rubygame::NamedResource’ in your class definition.

  2. Set MyClass.autoload_dirs to an Array of directories to look for files when autoloading. Tip: use File.join to create paths that work on any operating system.

  3. Define autoload to implement the behavior for your class, or leave it as the default if you don’t need autoloading. See the docs for autoload for more information.

Here’s an example of how you could use this for a class which loads maps from a file:

class Map
  include Rubygame::NamedResource

  Map.autoload_dirs = [ File.join("maps","world_1"),
                        File.join("maps","custom") ]

  def autoload( name )
    # Searches autoload_dirs for the file
    path = find_file( name )

    if( path )
      return load_map( path )
    else
      return nil
    end
  end

  def load_map( path )
    # Your code to do the real loading, then return
    # the created instance of Map class.
    # ...
    return map_instance
  end
end

Here’s an example of how you could then use the Map class:

map = Map["level_1.map"]

if( map )
  start_playing( map )
else
  raise "Oops! The map file for Level 1 doesn't exist!"
end

Public Instance Methods

name() click to toggle source

Returns the instance’s @name. See also name=.

# File lib/rubygame/named_resource.rb, line 222
def name
  @name
end
name=( new_name ) click to toggle source

Sets the instance’s @name to the given String, or nil to unset the name. See also name.

NOTE: This does not automatically store the instance in the class resource table by name. Use the #[]= class method to do that.

The string is dup’ed and frozen before being stored.

May raise: TypeError, if new_name is not a String or nil.

# File lib/rubygame/named_resource.rb, line 238
def name=( new_name )
  if new_name.nil?
    return @name = nil
  end

  unless new_name.kind_of? String
    raise TypeError, "name must be a String (got #{new_name.class})"
  end

  @name = new_name.dup
  @name.freeze
end

[Validate]

Generated with the Darkfish Rdoc Generator 2.