Autonomous Machine

Posts tagged with MongoDB

Store Hashie::Mash objects in Mongoid Documents

I've started using Mongoid's support for abitrary field types on a project. It involves working with a lot of nested hashes that are the result of parsing JSON, and I've found wrapping a Hashie::Mash around these data structures helps keep the code interacting with them clean:

doc.data.key.another_key.and_another_key
# vs
doc.data['key']['another_key']['and_another_key']

Since Hashie::Mash objects are just a subclass of Ruby's standard Hash, they can be stored in a field that's defined as a Hash in Mongoid:

class Doc
  include Mongoid::Document
  field :data, type: Hash
end

But when these documents are loaded back out of the database, the data field will contain a standard Hash. I'd like these hashes to be Hashie::Mash instances. To accomplish this, I defined a new column type for Mongoid called Mashed:

class Mashed
  include Mongoid::Fields::Serializable

  def deserialize(object)
    Hashie::Mash.new(object)
  end

  def serialize(object)
    Hash[object]
  end
end

That's all that is required to create a new column type in Mongoid, which can be specified just like any other in your document class:

class Doc
  include Mongoid::Document
  field :data, type: Mashed
end

Now I can save and load documents with Hashie::Mash fields. This is a trivally simple example, but by replacing the implementations of deserialize and serialize above, just about any kind of object could be persisted in a Mongoid document.

  • March 24, 2012
  • Article
  • MongoDB, Mongoid, Ruby