Namespaces - Archer70/desmond GitHub Wiki
Namespaces in Desmond are very simple. They can be thought of as named containers for symbols, which help to separate your code into smaller chunks. Let's start things right off with an example.
(namespace custom-space
(define my-sym "yay")
)
my-sym
;#> my-sym
custom-space/my-sym
;#> "yay"
As you can see above, we're defining a new namespace custom-space, wherein we also define a symbol my-sym. Later we prove that calling my-sym outside of the namespace only returns the symbol itself, because it's undefined. However, if we prefix the symbol with the namespace custom-space and a slash, it returns the value of custom-space/my-sym.
Namespace names are not actually "smart", in that they're just plain symbols used internally to refer to a collection of other symbols. Any valid symbol is a valid namespace, and does not have to refer to a file path. Though if you want to use the file path convention, you can also use autoloading, which is what we'll get into next.
This was taken from one of Desmond's unit test files.
(define autoload-get-file (lambda [symbol]
(let
{
chunks (split "/" symbol)
ns-chunks (pop chunks)
namespace (join "/" ns-chunks)
}
(str _dir "/" namespace ".dsmnd")
)
))
(autoload (lambda [symbol]
(load-file (autoload-get-file symbol))
))
First we define a function to help us get the file name we're loading, based on a symbol. The function breaks the path apart by it's directory separators /, pops the last piece off (the symbol contained in the namespace), and joins the remaining pieces, prefixed with the file-level _dir symbol.
autoload-get-file would be used as follows, to remove the symbol from the end, leaving the file path.
(autoload-get-file core/main/my-sym)
;#> /home/user/app/core/main.dsmnd
Now autoload takes a lambda function, which gets passed every symbol containing forward slashes. That lambda simply loads the file we get from autoload-get-file.
OPTIMIZATION HINT: Depending on how your app is set up, you may or may not want the autoloader to load the same file over and over again if you repeatedly use the same symbols. Therefore you may wish to implement a function that checks if a file has already been loaded. It's up to you to do that if desired.