Manage configuration in Rails way on node.js by using inheritance
Application is usually required to run in different environments. To manage the differences between the environments, we usually introduce the concept of Environment Specific Configuration. In Rails application, by default, Rails have provided 3 different environments, they are the well known, development, test and production. And we can use the environment variable RAILS_ENV to tell Rails which environment to be loaded, if the RAILS_ENV is not provided, Rails will load the app in development env by default.
This approach is very convenient, so we want to apply it to anywhere. But in node.js, Express doesn’t provide any configuration management. So we need to built the feature by ourselves.
The environment management usually provide the following functionalities:
Allow us to provide some configuration values as the default, which will be loaded in all environments, usually we call it common.
Specific configuration will be loaded according to the environment variable, and will override some values in the common if necessary.
Rails uses YAML to hold these configurations, which is concise but powerful enough for this purpose. And YAML provided inheritance mechanism by default, so you can reduce the duplication by using inheritance.
JSON Syntax is not concise enough
Matching the brackets and appending commas to the line end are distractions
Lack of flexility
As an answer to these issues, I chose coffee-script instead of JSON. Coffee is concise. And similar to YAML, coffee uses indention to indicate the nested level. And coffee is executable, which provides a lot of flexibilities to the configuration. So we can implement a Domain Specific Language form
To do it, we need to solve 4 problems:
Allow dev to declare default configuration.
Load specific configuration besides of default one.
Specific configuration can overrides the values in the default one.
Code is concise, clean and reading-friendly.
Inspired by the YAML solution, I work out my first solution:
YAML is data centric language, so its inheritance is more like “mixin” another piece of data. So I uses underscore to help me to mixin the specific configuration over the default one, which overrides the overlapped values.