Class: Syntropy::ModuleLoader

Inherits:
Object
  • Object
show all
Defined in:
lib/syntropy/module.rb

Overview

The ModuleLoader class implemenets a module loader. It handles loading of modules, tracking of dependencies between modules, and invalidation of loaded modules (following a change to the module file).

A module may implement a route endpoint, a layout template, utility methods, classes, or any other functionality needed by the web app.

Modules are Ruby files that can import other modules as dependencies. A module must export a single value, which can be a class, a template, a proc, or any other Ruby object. A module can also export itself by calling ‘export self`.

Modules are referenced relative to the web app’s root directory, without the .rb extension. For example, for a site residing in /my_site, the reference _lib/foo will point to a module residing in /my_site/_lib/foo.rb.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(env) ⇒ void

Instantiates a module loader

Parameters:

  • environment hash



29
30
31
32
33
34
# File 'lib/syntropy/module.rb', line 29

def initialize(env)
  @root_dir = env[:root_dir]
  @env = env
  @modules = {} # maps ref to module entry
  @fn_map = {} # maps filename to ref
end

Instance Attribute Details

#modulesObject (readonly)

Returns the value of attribute modules.



23
24
25
# File 'lib/syntropy/module.rb', line 23

def modules
  @modules
end

Instance Method Details

#invalidate_fn(fn) ⇒ void

This method returns an undefined value.

Invalidates a module by its filename, normally following a change to the underlying file (in order to cause reloading of the module). The module will be removed from the modules map, as well as modules dependending on it.

Parameters:

  • module filename



54
55
56
57
58
# File 'lib/syntropy/module.rb', line 54

def invalidate_fn(fn)
  ref = @fn_map[fn]
  invalidate_ref(ref) if ref
  invalidate_collection_modules
end

#load(ref) ⇒ any

Loads a module (if not already loaded) and returns its export value.

Parameters:

  • module reference

Returns:

  • export value



40
41
42
43
44
45
# File 'lib/syntropy/module.rb', line 40

def load(ref)
  ref = "/#{ref}" if ref !~ /^\//

  entry = (@modules[ref] ||= load_module(ref))
  entry[:export_value]
end