Autonomous Machine

Posts tagged with Mongoid

Use Active Model Serializers with Mongoid

I'm adding some new features to Forkchop using Ember, ember-rails, and the associated active_model_serializers. The only hiccup is that I'm using Mongoid, and Active Model Serializers only hooks into Active Record when it loads. This means that Rails doesn't automatically look for the appropriate serializer when using render json: @object.

To remedy this, I added the following lines from this Gist to config/initializers/mongoid_active_model_initializers:

Mongoid::Document.send(:include, ActiveModel::SerializerSupport)
Mongoid::Criteria.delegate(:active_model_serializer, to: :to_a)
  • May 05, 2012
  • Article
  • Active Model Serializers, Ember, Mongoid, Rails

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