mutations
mutations copied to clipboard
ensure symbolic error keys remain symbols
Previously, when doing this
add_error(:foo, :bar, "baz")
one could not fetch the error by that symbol, only by string.
outcome.errors["foo"]
This PR makes a tiny change to preserve the symbol keys.
outcome.errors[:foo]
Nice find, @estraph! It looks like this used to work correctly, but broke all the way back in https://github.com/cypriss/mutations/pull/3 🙂
Unfortunately I don't think we can just change it back: if the only way to access errors for the last five years has been to use a string, there will be a lot of code out there that does that. If we released a new version with this change, all of that code would break unless it was also updated to use symbols.
What do you think of making ErrorHash
inherit from HashWithIndifferentAccess
instead? That way strings will continue to work, but symbols will work too.
Great idea, I'll give that a shot. Good point about compatibility.
Inheriting from HashWithIndifferentAccess
was proposed in https://github.com/cypriss/mutations/pull/48, and rejected with this explanation:
If you have nested hashes in your inputs, and a field in a subhash is invalid, you get nested error hashes. HashWithIndifferentAccess clobbers these subhashes and removes the ErrorsHash from them, making them normal HashWithIndifferentAccess.
That behaviour was fixed in Rails 3.2.0 by https://github.com/rails/rails/commit/3d6eafe32ed498784dba2b9782bbf7df47ebeb6b; if we want to switch to inheriting from HashWithIndifferentAccess
, we would have to declare 3.2.0 to be the minimum compatible version of Active Support. That seems reasonable to me, as Rails 3.x has been unsupported for some time.
We should add a test for the behaviour of nested error hashes described in that comment too.