Class: DXOpal::RemoteResource

Inherits:
Object
  • Object
show all
Defined in:
lib/dxopal/remote_resource.rb

Overview

A base class for resources acquired through JS Promises. Provides `<klass>.register` and `<klass>`. A subclass must impelment `<klass>._load`.

TODO: better name? (SoundEffect is not actually 'remote')

Direct Known Subclasses

Image, Sound

Constant Summary collapse

@@resources =

List of registered resources (Contains path_or_url)

Hash.new{|h,k| h[k] = {}}
@@promises =

Contains promises

Hash.new{|h,k| h[k] = {}}
@@instances =

Contains instances of Image, Sound

Hash.new{|h,k| h[k] = {}}
@@klasses =

Subclasses of RemoteResource

{}

Class Method Summary collapse

Class Method Details

.[](name) ⇒ Object

Return instance of loaded resource (call on subclasses)



28
29
30
31
32
33
34
# File 'lib/dxopal/remote_resource.rb', line 28

def self.[](name)
  if (ret = @@instances[_klass_name][name])
    return ret
  else
    raise "#{_klass_name} #{name.inspect} is not registered"
  end
end

._klass_nameObject

Return a string like “Image” or “Sound”



63
64
65
# File 'lib/dxopal/remote_resource.rb', line 63

def self._klass_name
  return self.name.split(/::/).last
end

._load(*args) ⇒ Object

Load actual content (defined on subclasses) Return `[instance, promise]`



58
59
60
# File 'lib/dxopal/remote_resource.rb', line 58

def self._load(*args)
  raise "override me"
end

._load_resources(&block) ⇒ Object

Called from Window.load_resources



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/dxopal/remote_resource.rb', line 37

def self._load_resources(&block)
  @@resources.each do |klass_name, items|
    klass = @@klasses[klass_name] 
    items.each do |name, (block2, args)|
      if !@@promises[klass_name][name]
        instance, promise = klass._load(*args, &block2)
        @@instances[klass_name][name] = instance
        @@promises[klass_name][name] = promise
      end
    end
  end
  promises = @@promises.values.flat_map(&:values)
  %x{
    Promise.all(#{promises}).then(function() {
      #{block.call}
    });
  }
end

.add_class(subklass) ⇒ Object



17
18
19
# File 'lib/dxopal/remote_resource.rb', line 17

def self.add_class(subklass)
  @@klasses[subklass._klass_name] = subklass
end

.register(name, *args, &block) ⇒ Object

Reserve instance generation



22
23
24
25
# File 'lib/dxopal/remote_resource.rb', line 22

def self.register(name, *args, &block)
  @@resources[_klass_name] ||= {}
  @@resources[_klass_name][name] = [block, args]
end