Mongo Mapper

Validations

MongoMapper uses ActiveModel:Validations, so it works almost exactly like ActiveRecord.

class Person
  include MongoMapper::Document

  key :first_name,  String
  key :last_name,   String
  key :age,         Integer
  key :born_at,     Time
  key :active,      Boolean
  key :fav_colors,  Array

  validates_presence_of :first_name
  validates_presence_of :last_name
  validates_numericality_of :age

  validate :custom_validation

  def custom_validation
    if age < 20
      errors.add( :age, "Youth is wasted on the young")
    end
  end
end

Validations are run when attempting to save a record. If validations fail, save will return false.

@person = Person.new(:first_name => "Jon", :last_name => "Kern", :age => 9)
if @person.save
  puts "#{p.first_name} #{p.last_name} (age #{p.age})"
else
  puts "Error(s): ", p.errors.map {|k,v| "#{k}: #{v}"}
end
# Error(s):
# age: Youth is wasted on the young

Shorthand

Most simple validations can be declared along with the keys.

class Person
  include MongoMapper::Document

  key :first_name,  String,   :required => true
  key :last_name,   String,   :required => true
  key :age,         Integer,  :numeric => true
  key :born_at,     Time
  key :active,      Boolean
  key :fav_colors,  Array
end

The available options when defining keys are:

Fork me on GitHub