markbates / configatron

A super cool, simple, and feature rich configuration system for Ruby apps.

Home Page:http://www.metabates.com

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Suggestion: Unset keys should be falsy

DannyBen opened this issue · comments

I love configatron, but although it solves a lot of things, it makes it rather difficult to work with unassigned keys.

In a standard hash, or an OpenStruct, non existing values are falsy:

o = OpenStruct.new({ one: '1', two: '2' })
p o.three
# => nil

While in configatron they are truthy:

# configatron.allow = false   # unset
p configatron.allow ? "allowed" : "not allowed"
# => "allowed" (but expected "not allowed")

Even if I want to set defaults, I cannot work with the common ruby syntax:

configatron.allow ||= false

And instead, I can only do:

configatron.allow = false unless configatron.has_key? :allow

And in cases where I can't (or prefer to avoid) having defaults, in order to allow "open schema", the only way for me to handle unset keys in the same way as falsy keys, is:

allowed = configatron.has_key?(:allow) ? configatron.allow : false
p allowed ? "allowed" : "not allowed"

Am I missing some functionality in configatron that will make this easier?

If there is no way to alleviate the above issues, I would love to see a change that allows it - even if it will require me to opt-in to this behavior using some config directive (in case it is desired to avoid introducing a breaking change).

After looking at the code a little I found a way to do what you want.

[14] pry(main)> configatron.fetch(:helloworld, true)
=> true
[15] pry(main)> configatron.fetch(:helloworld)
=> true
[16] pry(main)> configatron.fetch(:foobarbaz)
=> nil

The [] method of the Store class seems to be a mere wrapper around fetch.

I think you shouldn't use the fetch method because then your request would lack an exit door when the store is locked. (See store.rb#L41.) Shouldn't this step be moved in the fetch function ? Then it should be possible to use it to pass a default value ?

I have made a little something by merging [] and fetch together that behaves like the following:

[3] pry(main)> configatron.allow
=> nil

I'm opening a pull request so we can discuss that.

So I was clearly mistaken - sry guys!