Mongo Mapper


MongoMapper provides ActiveModel-compatible serialization for building an XML or JSON representation of your model.

class User
  include MongoMapper::Document

  key :name,        String
  key :email,       String
  key :friend_ids,  Array

  many :interests
  many :friends, :class_name => 'User', :in => :friend_ids

  def newest_friend

class Interest
  include MongoMapper::EmbeddedDocument

  key :title, String

user = User.create(:name => "Foo", :email => "",
    :interests => [ => "Movies")])

Call to_json or to_xml on your model to return a serialized string, or serializable_hash to simply return a plain Ruby hash.

  "id":       "4da66b02217dd45643000323",
  "name":     "Foo",
  "email":    "",
  "interests": [
    {"id": "4dac5bd2c198a708f5000001", "title": "Movies"}
<?xml version="1.0" encoding="UTF-8"?>
  <interests type="array">

Note that embedded documents are included in the serialized output without any intervention.

Customizing Serialized Output

The to_json and to_xml methods take a few options, namely :only, :except and :include. The first two are straightforward filters for the generation of the serialized output.

user.to_json(:only => :name)

user.to_json(:except => :email)

:include lets you include an association or the result of a method in the serialized output.

user.to_json(:include => [:friends])

:methods lets you include the result of a method

user.to_json(:methods => [:newest_friend])

Internally, the serializable_hash method is used on your model to generate the serialized string. Override it provide your own implementation or to set defaults.

  def serializable_hash(options = {})
    super({:except => :password}.merge(options))
Fork me on GitHub