I’ve been writing a lot of Coldbox modules lately, and I noticed there are two places where your module’s version lives:
1. box.json version key.
This is the super important one, especially if you publish your module to Forgebox. You should always keep it up to date either manually or via commandbox’s bump command.
2. ModuleConfig.cfc this.version.
I’m not really sure what the purpose of this value is, other than Coldbox saves a reference to it when it registers a module. You can access the version by calling getModuleConfig( "modulename" ).version;
Now lets say you created a really cool module and you want to display the version somewhere, but you don’t want to always keep the box.json version and the ModuleConfig.cfc in sync. Well, now you don’t have to! If you modify your ModuleConfig.cfc to grab the version directly from box.json when your app starts, you can have it populate automatically with every fwreinit.
Example:
// ModuleConfig.cfc
// The version is NOT hardcoded here. box.json is the single source of truth.
this.version = readPackageVersion();
And, as a private method alongside the other private helpers:
/**
* Read this module's version from box.json
* CommandBox, ForgeBox and the build (`package show version`) all read box.json
*
* @return The semver from box.json, or "" if it cannot be read.
*/
private string function readPackageVersion(){
// A missing or unreadable box.json must never stop the module from REGISTERING
try {
var boxJsonPath = getDirectoryFromPath( getCurrentTemplatePath() ) & "box.json";
if ( !fileExists( boxJsonPath ) ) {
return "";
}
var boxJson = deserializeJSON( fileRead( boxJsonPath ) );
return structKeyExists( boxJson, "version" ) ? boxJson.version : "";
} catch ( any e ) {
return "";
}
}