Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 14 additions & 12 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,11 @@ Declare a module (one per file) that other modules can load by calling `import`
with a relative filepath. `export` takes a single block parameter whose return
value is what gets exported from the module.

#### export(key, value)

Declare a single export from a module. This will make it so that your
module exports a hash with `{key => value}`.

#### import(id)

Load another module. `import` works with local modules declared with `export` as
Expand All @@ -72,28 +77,25 @@ import('test/unit/assertions') =>
### Example

```rb
### foo.rb
export do
# The value you return from the export block is what gets exported
# from the module.
'foo'
end
### consts.rb
export :foo, 'foo'
export :bar, 'bar'

### foo_wrapper.rb
# Load the 'foo' constant from foo.rb
foo = import './foo'
### foobar.rb
# Load the constants from consts.rb
consts = import './consts'

export do
lambda { foo }
lambda { consts[:foo] + consts[:bar] }
end

### test.rb
# load local modules defined with an amd-inspired syntax
foo = import './foo_wrapper'
foobar = import './foobar'
# compatible with external globals-style ruby modules
assert = import('test/unit/assertions')['Test::Unit::Assertions']

assert.assert_equal(foo.call(), 'foo')
assert.assert_equal(foobar.call(), 'foobar')
# No global namespace pollution \o/
assert.assert_equal(defined? Test, nil)
```
Expand Down
11 changes: 2 additions & 9 deletions example/modular.rb
Original file line number Diff line number Diff line change
@@ -1,9 +1,2 @@
export do
add = import './add'
multiply = import './multiply'

{
add: add,
multiply: multiply,
}
end
export :add, import('./add')
export :multiply, import('./multiply')
9 changes: 7 additions & 2 deletions lib/global.rb
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
require_relative './loader'

class Object
def export
value = yield
def export(name=nil, value=nil)
if name.nil?
value = yield
else
value = {name => value}
end

Loader.export(value)
end

Expand Down
7 changes: 6 additions & 1 deletion lib/loader.rb
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,12 @@ module Loader
@path = nil

def self.export(value)
@cache[@path] = value
if @cache.include?(@path) && value.class == Hash
# Special handling to enable multiple exports
@cache[@path] = @cache[@path].merge(value)
else
@cache[@path] = value
end
end

def self.import(id, type=nil)
Expand Down