Class: CommonJS::Environment

Inherits:
Object
  • Object
show all
Defined in:
lib/commonjs/environment.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(runtime, options = {}) ⇒ Environment

Returns a new instance of Environment.



7
8
9
10
11
# File 'lib/commonjs/environment.rb', line 7

def initialize(runtime, options = {})
  @runtime = runtime
  @paths = [options[:path]].flatten.map {|path| Pathname(path)}
  @modules = {}
end

Instance Attribute Details

#runtimeObject (readonly)

Returns the value of attribute runtime.



5
6
7
# File 'lib/commonjs/environment.rb', line 5

def runtime
  @runtime
end

Instance Method Details

#native(module_id, impl) ⇒ Object



23
24
25
# File 'lib/commonjs/environment.rb', line 23

def native(module_id, impl)
  @modules[module_id] = Module::Native.new(impl)
end

#new_objectObject



27
28
29
# File 'lib/commonjs/environment.rb', line 27

def new_object
  @runtime['Object'].new
end

#require(module_id) ⇒ Object



13
14
15
16
17
18
19
20
21
# File 'lib/commonjs/environment.rb', line 13

def require(module_id)
  unless mod = @modules[module_id]
    filepath = find(module_id) or fail LoadError, "no such module '#{module_id}'"
    load = @runtime.eval("(function(module, require, exports) {#{File.read(filepath)}})", filepath.expand_path.to_s)
    @modules[module_id] = mod = Module.new(module_id, self)
    load.call(mod, mod.require_function, mod.exports)
  end
  return mod.exports
end