March 7, 2015 by Daniel P. Clark

Configuration With a Singleton Instance

I was considering how I might want to further implement my gem and incorporate configuration settings for it.  I wanted only one instance of my configuration and it needed to be part of my module.  So I’ve come up with a solution I like that allows me to do this and even have a true “sense” of untouchable constants.

I’ve found OpenStruct to be for my liking in this situation as it allows for any configuration (variable) to be set on it.  I’ve also found I can set “unalterable” variables… at least through standard assignment options.

Here’s the basics of it:

The reason I created the class MyProject::MyConfig just to inherit OpenStruct is that I want my configuration to be identified by a class name that indicates it is a config object that belongs to my project.  In module MyProject I use attr_reader for config because we are getting the OpenStruct instance handed back to us and we can still invoke method/value assignment on it.  I use the single class variable @config for the internal singleton value because it’s not going anywhere (No need to use @@config).  The method config is defined on the singleton instance of the module MyProject via the class << self.  So to set any value all I need to do is MyProject.config.new_value = 42.

If I want to set a constant value that I don’t want to change then all I have to do is define the method within the OpenStruct instance.  You can do it in the class, or open it up with the singleton opener.

If you want a default value that can be updated; then you may implement that method with a method_missing(:method_name) || :value .  As soon as you assign a new value it will choose the updated value.


So now you can have a single instance configuration that’s easily updatable and you can set values that you don’t want to change.  I do realize that the “constants” in this case aren’t defined the way the language normally defines constants.  But in this situation it’s what works… and it works better than constants that don’t truly stay constant when reassigned ;-).

I hope this was informative and enjoyable for you!  Please feel free to comment, share, subscribe to my RSS Feed, and follow me on twitter @6ftdan!

God Bless!
-Daniel P. Clark

Image by murray 9000 via the Creative Commons Attribution-NonCommercial-NoDerivs 2.0 Generic License