There are a lot of gems to handle settings within your Ruby on Rails app. I’ve used Rails Settings Cached previously and I found it good for app-wide settings. I didn’t find it great for model-by-model settings.
So I wrote Setsy, a Ruby gem for handling settings. Setsy is relatively simple but very effective library in handling settings on a model-by-model basis. I originally wrote this for my new project, Storefronting, a store locator app, and it’s been a treat. I use it on an object that holds collections of stores on a map. These settings are for things like initial distance for showing stores, setting the default zoom level, initial lat/lng of the map, stuff like that.
Prior to writing Setsy I had a few options.
One was using a JSON column for settings. That would work fine, yeah, but it wouldn’t automatically coerce the values when read again. They’d all be strings, and that’d be a pain.
One was having a lot of database columns. That’d be great, it’d work fine with form objects, querying would be fine. But it’d be so nasty to maintain.
Another was an entirely different polymorphic model. That’s a no.
With a stomach ache just thinking about all options, I quickly hacked together an initial “let’s see how this goes.” I’d copy-pasta code here, but it’s really not that different from what’s on Github now, give a line-or-two.
Setsy is different in that it casts things just how ActiveRecord does with ActiveModel. This means you can have the types you want, backed by ActiveRecord, without having to worry about casting them yourself. This is done by looking up the default value against ActiveModel::Typeand casting the new type.
To conclude, it’s a relatively simple amount of code to write and test that I’m sure I’ll use in the future. Why not share it?