Get a Struct or Array in That Simple Value Field
In some environments and scenarios, I used to use initialization (*.ini) files for storing simple configuration settings. Now I typically store this kind of information in a ColdSpring configuration file, or at least in an XML file of some sort. But at times I have to live (and work) with the apps I wrote that use *.ini configuration files.
The nice thing about *.ini files. Not that they're all bad. It's ridiculously easy to extract settings from these files with ColdFusion. For instance:
-
[Settings]
-
mysetting=Hello
-
anothersetting=Goodbye
To retrieve the mysetting configuration setting, I just make one call:
-
x=GetProfileString(pathToFile,"Settings","mysetting");
It can't get much easier than that to retrieve a value from a configuration file!
The bad thing about *.ini files. The only problem is that these files are restricted to name=value pairs of simple values. You may go into a project with no need for configuration settings that are any more complicated than simple numbers or strings, but what about 3 years from now when the business logic now could use some structs or arrays in the configuration?
Of course, you could change your whole configuration methodology when--and if--that time comes, but ugh. Using XML (especially in conjunction with IoC such as ColdSpring) is so much more scalable. The future you will thank you.
But it's too late. You and I already have complex app XYZ that is using *.ini config files, and you need to add feature X without rebuilding the configuration logic of the app. What to do?
Embed a string representation of your struct or array in the config file! After all, ColdFusion 8 allows implicit struct and array creation, right? Well, half-right. Doing something like x=Evaluate(myStructString) just isn't allowed by ColdFusion.
However, we can effectively do the same thing with JSON representations of structs and arrays. So, try this:
-
[Settings]
-
mysetting={"one":"Hello","two":"Goodbye"}
-
anothersetting=Yomomma
Now, retrieving mysetting with GetProfileString() will still get you a string, but using JSON functions built into ColdFusion 8 will get you a struct:
-
x=GetProfileString(pathToFile,"Settings","mysetting");
-
myStruct=DeserializeJSON(x);
Your myStruct variable will be a struct with two keys ("one" and "two") just as you would expect from the JSON.
You could achieve similar results using XmlParse(), but in a case like this, the less verbose, the better. And JSON is less verbose than XML.
