Global Settings With Mongo and Rails in 15 Lines of Code

There is a nice ActiveRecord Rails plugin called rails-settings that does the following:

Settings is a plugin that makes managing a table of global key, value pairs easy. Think of it like a global Hash stored in you database, that uses simple ActiveRecord like methods for manipulation. Keep track of any global setting that you dont want to hard code into your rails app. You can store any kind of object. Strings, numbers, arrays, or any object.

We have used this plugin in the past for global key / value pairs and it works great. However, for our Floxee app, we are using MongoDB / MongoRecord so this plugin would not work.

Lucky for us, MongoDB is already a document store so I was able to recreate similar code in about 15 lines of code inside of a “method_missing” method.

With this, we are now able to do things like:

>> AppSetting.jim = "is cool"
=> "is cool"

>> AppSetting.arr = ["jim", "was", "here"]
=> ["jim", "was", "here"]

>> AppSetting.arr.first
=> "jim"

>> AppSetting.hsh = {"hash_1"=>1, "hash_2"=>"demo"}
=> {"hash_1"=>1, "hash_2"=>"demo"}

>> AppSetting.hsh["hash_2"]
=> "demo"

  •