Module: Gamefic::Autoload

Defined in:
lib/gamefic/autoload.rb,
lib/gamefic/autoload/version.rb

Overview

A Zeitwerk autoloader for Gamefic.

Gamefic::Autoload gives the Gamefic SDK a way to use Zeitwerk’s code loading conventions in Opal-based web apps.

Constant Summary collapse

VERSION =
'1.1.0'

Class Method Summary collapse

Class Method Details

.encode(directory) ⇒ Array<String>

Translate a directory’s load history into lines of Ruby source code that can replicate the autoload process without Zeitwerk.

Parameters:

  • directory (String)

Returns:

  • (Array<String>)


49
50
51
52
53
54
55
56
57
58
# File 'lib/gamefic/autoload.rb', line 49

def self.encode(directory)
  history(directory).map do |hash|
    if File.file?(hash[:file])
      path = hash[:file].sub(%r{^#{directory}/?}, '').sub(/\.rb$/, '')
      "require '#{path}'"
    else
      "#{hash[:const].is_a?(Class) ? 'class ' : 'module'} #{hash[:const]}; end"
    end
  end
end

.encode_allArray<String>

Encode all of the registered directories.

Returns:

  • (Array<String>)


63
64
65
# File 'lib/gamefic/autoload.rb', line 63

def self.encode_all
  registered.flat_map { |directory| encode(directory) }
end

.history(directory) ⇒ Array<Hash>

The history of a directory’s load events.

Returns:

  • (Array<Hash>)


39
40
41
42
# File 'lib/gamefic/autoload.rb', line 39

def self.history(directory)
  registry[directory].eager_load
  histories[directory]
end

.registeredArray<String>

A list of all the directories that use autoloading.

Returns:

  • (Array<String>)


32
33
34
# File 'lib/gamefic/autoload.rb', line 32

def self.registered
  registry.keys
end

.setup(directory, namespace: Object) {|| ... } ⇒ Zeitwerk::Loader

Enable autoloading in a directory. See the Zeitwerk documentation for more information.

Parameters:

  • directory (String)

    The directory name

  • namespace (Module) (defaults to: Object)

    The directory’s root namespace

Yield Parameters:

  • (Zeitwerk::Loader)

Returns:

  • (Zeitwerk::Loader)


21
22
23
24
25
26
27
# File 'lib/gamefic/autoload.rb', line 21

def self.setup(directory, namespace: Object, &block)
  if RUBY_ENGINE == 'opal'
    Gamefic.logger.info 'Opal engine detected - Gamefic::Autoload skipped'
  else
    register_and_setup directory, namespace, &block
  end
end