Ruby - Module Attribute Accessors and Defaults
So, I was building a gem on which I had a LOT of configurable defaults.
This called for the usual suspects - class variables and mattr_accessor
(which is provided by active_support's core extensions)
So I ended up with something on the likes of this:
module MyWonderfulGem
@@one_thing = "hello"
mattr_accessor :one_thing
@@another_thing = "world"
mattr_accessor :another_thing
# ........
end
Doing this for a couple of attribute accessors is acceptable but if you have a few dozens, then it becomes a bit cumbersome... Again, activesupport comes to the rescue as it provides the `attraccessorwithdefault`. So the code turns into something like this:
module MyWonderfulGem
attr_accessor_with_default :one_thing, "hello"
attr_accessor_with_default :another_thing, "world"
# ........
end
Not too bad but it forces me to keep writing the attr_accessor_with_default
keyword... Draaaaagghhh...
So, and because I'm a lazy developer and I hate repetition, I decided that I should implement my own solution, and I came up with something that allows me to write my code like this:
module MyWonderfulGem
module_attr_accessor one_thing: "hello", another_thing: "world"
# ........
end
I've made a gist with my core_ext to the Module class that allows me to write the code above, go check it out: module_attr_accessors