Mongo Mapper

Types

Because of MongoDB’s ability to store rich documents, MongoMapper supports most of Ruby’s data types out of the box, such as Array, Float, Hash, Integer, NilClass, Object, String, and Time. In addition to those, MongoMapper adds support for Binary, Boolean, Date, ObjectId, and Set by serializing to and from Mongo safe types.

Custom Types

The great thing about MongoMapper is that you can create your own types to make your models more pimp. All that is required to make your own type is to define the class and add the to_mongo and from_mongo class methods. For example, here is a type that always downcases strings when saving to the database:

class DowncasedString
  def self.to_mongo(value)
    value.nil? ? nil : value.to_s.downcase
  end

  def self.from_mongo(value)
    to_mongo(value)
  end
end

Or, if you are curious about a slightly more complex example, here is a type that is used in MongoMapper’s tests:

class WindowSize
  attr_reader :width, :height

  def self.to_mongo(value)
    value.to_a
  end

  def self.from_mongo(value)
    value.is_a?(self) ? value : WindowSize.new(value)
  end

  def initialize(*args)
    @width, @height = args.flatten
  end

  def to_a
    [width, height]
  end

  def eql?(other)
    self.class.eql?(other.class) &&
       width == other.width &&
       height == other.height
  end
  alias :== :eql?
end

This example actually serializes to an array for storage in Mongo, but returns an actual WindowSize object after retrieving from the database.

Fork me on GitHub