Module: Ray::ResourceSet

Included in:
Font, FontSet, Image, ImageSet, SoundBuffer, SoundBufferSet
Defined in:
lib/ray/resource_set.rb

Overview

Mixin used to cache resources. It allows to register different block to create the resources using a regexp:

add_set(/^http://(.+)$/) do |url| # captures are passed to the block
  ...
end

Custom arguments can also be specified:

add_set(/^http://(.+)/) do |url, priority| # arguments are passed at the end
  ...
end

Notice you would usually use extend instead of include to use this module.

Instance Method Summary collapse

Instance Method Details

#[](key) ⇒ Object

Returns The object corresponding to a given string.

Returns:

  • The object corresponding to a given string.



32
33
34
35
36
37
38
# File 'lib/ray/resource_set.rb', line 32

def [](key)
  set_hash.each do |regexp, hash|
    return hash[key] if regexp =~ key
  end

  missing_pattern(key)
end

#add_set(regexp, &block) ⇒ Object

Registers a block for handling some resources.



20
21
22
23
24
25
# File 'lib/ray/resource_set.rb', line 20

def add_set(regexp, &block)
  set_hash[regexp] = Hash.new do |hash, key|
    key =~ regexp
    hash[key] = yield(*$~.captures)
  end
end

#clearObject

Removes all the items from the resource set



65
66
67
# File 'lib/ray/resource_set.rb', line 65

def clear
  set_hash.each { |regexp, hash| hash.clear }
end

#missing_pattern(string) ⇒ Object

Method called when a string isn’t matched by any pattern. Raises a NoPatternError excpetion by default.

Raises:



71
72
73
# File 'lib/ray/resource_set.rb', line 71

def missing_pattern(string)
  raise NoPatternError, "#{string.inspect} not macthed by any pattern"
end

#reject! { ... } ⇒ Object Also known as: delete_if

Removes all the objects from the array but those for which block returned true.

Yields:

  • key, object (See #select!)



57
58
59
60
# File 'lib/ray/resource_set.rb', line 57

def reject!
  return Enumerator.new(self, :reject!) unless block_given?
  select! { |key, obj| !yield(key, obj) }
end

#select! {|key, object| ... } ⇒ Object

Selects objects matching a condition.

Yields:

  • key, object

Yield Parameters:

  • key

    the key used to refer to the resource

  • object

    the actual resource



45
46
47
48
49
50
51
# File 'lib/ray/resource_set.rb', line 45

def select!
  return Enumerator.new(self, :select!) unless block_given?

  set_hash.each do |regexp, hash|
    hash.delete_if { |key, val| !yield(key, val) }
  end
end

#set_hashObject



27
28
29
# File 'lib/ray/resource_set.rb', line 27

def set_hash
  (@set_hash ||= {})
end