If you supply Mongo with a hash that uses symbols as keys and save the document, it will ‘stringify’ it, meaning the keys will be converted to strings. To summarize:
condition: hash keys will be: ---------- ------------------ after initializing a document symbols or strings after saving a document strings after fetching a document strings
This ‘asymmetry’ has led to some ugliness in my tests. I would like to be able to ‘rely on’ the keys always being strings – and not worry about if the document has just been initialized or not.
What are one or more elegant ways to avoid this?
Note: In my case, I’m using Mongoid, but I don’t think this question is necessarily Mongoid specific. It probably applies to any Rails project that uses MongoDB.
Something along these lines could work. Basically this code redefines Mongoid’s
fieldmacro (its setter).This may not be the cleanest implementation, but you get the idea.