Skip to content

Commit

Permalink
Fixing the handling of global modules (#9)
Browse files Browse the repository at this point in the history
Co-authored-by: Singla Valls <[email protected]>
  • Loading branch information
Dracks and Singla Valls authored Aug 19, 2023
1 parent ac114fd commit ba2f875
Show file tree
Hide file tree
Showing 4 changed files with 49 additions and 2 deletions.
22 changes: 22 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,3 +58,25 @@ mod.init()!
```

Also you can set a module as global creating it like `Module{global: true}`, once this is imported, the services of this module will be available accross all modules. **Only to be used with specific cases, but should not be used normally**


### Ways to register a service

* Existing instance
```vlang
mod.use_instance(instance, false)
```

* Using a Factory
```vlang
struct Dependencies {
some_dep &Dep [inject]
}
mod.use_factory(fn (dep &Dependencies) NewStruct {
return NewStruct{
something: dep.some_dep.count()
}
}, false)
``
1 change: 1 addition & 0 deletions src/module_init.v
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ pub fn (mut self Module) build_factories() ! {
has_instantiated_factories = false
for mut factory in factories_list {
if factory.can_instantiate() {
println('Instantiating factory of ${factory.typ}')
has_instantiated_factories = true
factory.build()!
factory.instantiated = true
Expand Down
25 changes: 24 additions & 1 deletion src/multi_module.v
Original file line number Diff line number Diff line change
@@ -1,5 +1,23 @@
module vest

import arrays

fn (self Module) get_all_childs(mut childs []&Module) {
for glob in self.globals {
if glob !in childs {
childs << glob
glob.get_all_childs(mut childs)
}
}

for mod in self.imports {
if mod !in childs {
childs << mod
mod.get_all_childs(mut childs)
}
}
}

pub fn (mut self Module) import_module(mut mod Module) {
if mod.global {
self.globals << mod
Expand All @@ -13,7 +31,12 @@ pub fn (mut self Module) import_module(mut mod Module) {
self.globals << global_mod
}
}
mod.globals = self.globals
mut childs := []&Module{}
childs << mod
mod.get_all_childs(mut childs)
for mut child_mod in childs {
child_mod.globals = self.globals
}
}
}

Expand Down
3 changes: 2 additions & 1 deletion src/register_service.v
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,8 @@ pub fn (mut self Module) use_factory[F, T](factory fn (c F) T, export bool) {
self.factories << &Factory{
typ: typ_idx
dependencies: dependencies
can_instantiate: fn [self, dependencies] () bool {
// TODO this mut self is a problem, I need to avoid passing self here
can_instantiate: fn [mut self, dependencies] () bool {
for dep_id in dependencies {
if !self.check_exist(dep_id, none) {
return false
Expand Down

0 comments on commit ba2f875

Please sign in to comment.