SlideShare a Scribd company logo
MongoMapper
Mapping Ruby To and From Mongo




MongoSF San Francisco, CA   John Nunemaker
April 30, 2010                    Ordered List
Using
Extending
Prophesying
Using
Extending
Prophesying
...and many more.
class Item
end
class Item
  include MongoMapper::Document
end
class Datum
  include MongoMapper::EmbeddedDocument
end
Free Stu
Free Stu
 Persistence
Free Stu
 Persistence
 Validations   [presence, length, inclusion, ...]
Free Stu
 Persistence
 Validations   [presence, length, inclusion, ...]


 Callbacks     [before/after validate, create, save, ...]
Free Stu
 Persistence
 Validations    [presence, length, inclusion, ...]


 Callbacks      [before/after validate, create, save, ...]


 Associations   [many, belongs_to, one, ...]
Free Stu
 Persistence
 Validations     [presence, length, inclusion, ...]


 Callbacks       [before/after validate, create, save, ...]


 Associations    [many, belongs_to, one, ...]


 Serialization   [to_json]
Persistence
Never gonna give you up
item = Item.create({
   :title    => 'MongoSF',
   :location => 'San Fran',
   :when     => Time.now
})
puts item.to_mongo

{
    "_id"        =>   ObjectID('4bd8cc5cbcd1b313b3000001'),
    "title"      =>   "MongoSF",
    "location"   =>   "San Fran",
    "when"       =>   Wed Apr 28 17:01:32 -0700 2010
}
item              =   Item.new
item[:title]      =   'MongoSF'
item[:location]   =   'San Fran'
item[:when]       =   Time.now
item.save
puts item.to_mongo

{
    "_id"        =>   ObjectID('4bd8cc5cbcd1b313b3000001'),
    "title"      =>   "MongoSF",
    "location"   =>   "San Fran",
    "when"       =>   Wed Apr 28 17:01:32 -0700 2010
}
Types
What you be baby boo?
class Item
  include MongoMapper::Document

  key :title, String
  key :path, String
end
But Mongo is Schema-less?
Instead of database schema

Think App Schema
Built-in Types
Array, Binary, Boolean, Date, Float, Hash,
Integer, Nil, ObjectId, Set, String, Time
Custom Types
Its shake and bake and I helped!
class Set
  def self.to_mongo(value)
    value.to_a
  end

  def self.from_mongo(value)
    Set.new(value || [])
  end
end
class DowncasedString
  def self.to_mongo(value)
    value.nil? ? nil : value.to_s.downcase
  end

  def self.from_mongo(value)
    value.nil? ? nil : value.to_s.downcase
  end
end
class User
  include MongoMapper::Document

  key :email, DowncasedString
end
Typeless
I do not know who I am
class Foo
  include MongoMapper::Document
  key :bar
end

foo = Foo.new

foo.bar = 'Some text'
# foo.bar => "Some text"

foo.bar = 24
# foo.bar => 24
Validations
Currently using fork of validatable
class Item
  include MongoMapper::Document

  key :title, String
  validates_presence_of :title
end
class Item
  include MongoMapper::Document

  key :title, String, :required => true
end
validates_presence_of
validates_length_of
validates_format_of
validates_numericality_of
validates_acceptance_of
validates_confirmation_of
validates_inclusion_of
validates_exclusion_of
Callbacks
Ripped from AS2’s cold, dead fingers
class Item
  include MongoMapper::Document

  key :title, String
  key :path, String
  key :parent_id, ObjectId
  belongs_to :parent

  before_validation :set_path

  private
    def set_path
      self.path = parent.path + title.parameterize
    end
end
:before_save,                   :after_save,
:before_create,                 :after_create,
:before_update,                 :after_update,
:before_validation,             :after_validation,
:before_validation_on_create,   :after_validation_on_create,
:before_validation_on_update,   :after_validation_on_update,
:before_destroy,                :after_destroy,
:validate_on_create,            :validate_on_update,
:validate
Associations
I belong to you
to Docs
belongs_to, one, many, many :in
class Account
  include MongoMapper::Document

  many :sites
end

class Site
  include MongoMapper::Document

  key :account_id, ObjectId
  belongs_to :account
end
account = Account.create(:title => 'OL', :sites => [
   Site.new(:title => 'OL', :domain => 'orderedlist.com'),
   Site.new(:title => 'RT', :domain => 'railstips.org'),
])
[
    {
         '_id'          =>   ObjectID('...'),
         'title'        =>   'OL',
         'domain'       =>   'orderedlist.com'
         'account_id'   =>   ObjectID('...'),
    },
    {
         '_id'          =>   ObjectID('...'),
         'title'        =>   'RT',
         'domain'       =>   'railstips.org'
         'account_id'   =>   ObjectID('...'),
    }
]
to Embedded Docs
many, one
class Item
  include MongoMapper::Document

  many :data
end

class Datum
  include MongoMapper::EmbeddedDocument

  key :key, String
  key :value
end
Item.create(:title => 'MongoSF', :data => [
   Datum.new(:key => 'description', :value => 'Awesome.')
])
{
    '_id'   => ObjectID('...'),
    'title' => 'MongoSF',
    'data' => [
      {
        '_id'   => ObjectID('...'),
        'key'   => 'description'
        'value' => 'Awesome.',
      }
    ]
}
Using
Extending
Prophesying
Plugins
Conventional way to extend
MongoMapper is

Powered by Plugins
associations, callbacks, clone, descendants,
dirty, equality, identity_map, inspect, keys,
logger, modifiers, pagination, persistence,
protected, rails, serialization, timestamps,
userstamps, validations
Ruby Development and MongoMapper (John Nunemaker)
Ruby Development and MongoMapper (John Nunemaker)
module MongoMapper
  module Plugins
    def plugins
      @plugins ||= []
    end

    def plugin(mod)
      extend mod::ClassMethods     if mod.const_defined?(:ClassMethods)
      include mod::InstanceMethods if mod.const_defined?(:InstanceMethods)
      mod.configure(self)          if mod.respond_to?(:configure)
      plugins << mod
    end
  end
end
module ActsAsListFu
  module ClassMethods
    def reorder(ids)
      # reorder ids...
    end
  end

  module InstanceMethods
    def move_to_top
      # move to top
    end
  end

  def self.configure(model)
    model.key :position, Integer, :default => 1
  end
end
class Foo
  include MongoMapper::Document
  plugin ActsAsListFu
end

Foo.reorder(...)
Foo.new.move_to_top
Good Example
Joint: github.com/jnunemaker/joint
class Asset
  include MongoMapper::Document
  plugin Joint

  attachment :image
  attachment :file
end
asset = Asset.create({
   :image => File.open('john.jpg', 'r'),
   :file  => File.open('foo.txt', 'r'),
})

asset.image.id
asset.image.name
asset.image.type
asset.image.size
asset.image.read
Descendant Appends
Fancy Schmancy and Stolen
module FancySchmancy
  def some_method
    puts 'some method'
  end
end

MongoMapper::Document.append_extensions(FancySchmancy)

class Foo
  include MongoMapper::Document
end

Foo.some_method     # puts 'some method'
Foo.new.some_method # NoMethodError
module FancySchmancy
  def some_method
    puts 'some method'
  end
end

MongoMapper::Document.append_inclusions(FancySchmancy)

class Foo
  include MongoMapper::Document
end

Foo.new.some_method # puts 'some method'
Foo.some_method     # NoMethodError
module FancySchmancy
  def some_method
    puts 'some method'
  end
end

class Foo
  include MongoMapper::Document
end

MongoMapper::Document.append_extensions(FancySchmancy)

class Bar
  include MongoMapper::Document
end

Foo.some_method # puts 'some method'
Bar.some_method # puts 'some method'
module IdentityMapAddition
  def self.included(model)
    model.plugin MongoMapper::Plugins::IdentityMap
  end
end

MongoMapper::Document.append_inclusions(IdentityMapAddition)
Using
Extending
Prophesying
Active Model
Validations, callbacks, serialization, etc.
Blank Document
Mix and match whatever you want
Mongo::Query
Fancy query magic for the ruby driver
github.com/jnunemaker/mongo-query
ideafoundry.info/mongodb
mongotips.com
railstips.org
Thank you!
john@orderedlist.com
@jnunemaker



MongoSF San Francisco, CA   John Nunemaker
April 30, 2010                    Ordered List

More Related Content

What's hot (19)

PDF
The Ring programming language version 1.5.4 book - Part 44 of 185
Mahmoud Samir Fayed
 
KEY
MTDDC 2010.2.5 Tokyo - Brand new API
Six Apart KK
 
PDF
The Ring programming language version 1.3 book - Part 34 of 88
Mahmoud Samir Fayed
 
PDF
Lodash js
LearningTech
 
PDF
Python dictionary : past, present, future
delimitry
 
PDF
The Rule of 10,000 Spark Jobs: Learning From Exceptions and Serializing Your ...
Databricks
 
PPTX
The Rule of 10,000 Spark Jobs - Learning from Exceptions and Serializing Your...
Matthew Tovbin
 
PDF
The Ring programming language version 1.2 book - Part 32 of 84
Mahmoud Samir Fayed
 
PPTX
JQuery Presentation
Sony Jain
 
KEY
Django Pro ORM
Alex Gaynor
 
PDF
Chaining and function composition with lodash / underscore
Nicolas Carlo
 
PDF
The Ring programming language version 1.6 book - Part 46 of 189
Mahmoud Samir Fayed
 
KEY
Introducing CakeEntity
Basuke Suzuki
 
PDF
Beyond Breakpoints: Advanced Debugging with XCode
Aijaz Ansari
 
PPTX
Django - sql alchemy - jquery
Mohammed El Rafie Tarabay
 
KEY
Introducing CakeEntity
Basuke Suzuki
 
PDF
MongoDBで作るソーシャルデータ新解析基盤
Takahiro Inoue
 
PDF
Functional es6
Natalia Zaslavskaya
 
PDF
MongoDB全機能解説2
Takahiro Inoue
 
The Ring programming language version 1.5.4 book - Part 44 of 185
Mahmoud Samir Fayed
 
MTDDC 2010.2.5 Tokyo - Brand new API
Six Apart KK
 
The Ring programming language version 1.3 book - Part 34 of 88
Mahmoud Samir Fayed
 
Lodash js
LearningTech
 
Python dictionary : past, present, future
delimitry
 
The Rule of 10,000 Spark Jobs: Learning From Exceptions and Serializing Your ...
Databricks
 
The Rule of 10,000 Spark Jobs - Learning from Exceptions and Serializing Your...
Matthew Tovbin
 
The Ring programming language version 1.2 book - Part 32 of 84
Mahmoud Samir Fayed
 
JQuery Presentation
Sony Jain
 
Django Pro ORM
Alex Gaynor
 
Chaining and function composition with lodash / underscore
Nicolas Carlo
 
The Ring programming language version 1.6 book - Part 46 of 189
Mahmoud Samir Fayed
 
Introducing CakeEntity
Basuke Suzuki
 
Beyond Breakpoints: Advanced Debugging with XCode
Aijaz Ansari
 
Django - sql alchemy - jquery
Mohammed El Rafie Tarabay
 
Introducing CakeEntity
Basuke Suzuki
 
MongoDBで作るソーシャルデータ新解析基盤
Takahiro Inoue
 
Functional es6
Natalia Zaslavskaya
 
MongoDB全機能解説2
Takahiro Inoue
 

Viewers also liked (10)

PPTX
MongoDB on Windows Azure
MongoDB
 
PDF
MongoHQ (Jason McCay & Ben Wyrosdick)
MongoSF
 
PDF
Practical Ruby Projects with MongoDB - Ruby Midwest
Alex Sharp
 
KEY
MongoDB - Ruby document store that doesn't rhyme with ouch
Wynn Netherland
 
PPTX
MongoDB Replication (Dwight Merriman)
MongoSF
 
PPTX
Cosmic rays detection theory
Lalit Pradhan
 
PPT
Cosmic Ray Presentation
guest3aa2df
 
PPTX
physics lecture
Jolie John Ej Cadag
 
KEY
MongoDB: How it Works
Mike Dirolf
 
PPTX
Solid state physics - Crystalline Solids
Athren Tidalgo
 
MongoDB on Windows Azure
MongoDB
 
MongoHQ (Jason McCay & Ben Wyrosdick)
MongoSF
 
Practical Ruby Projects with MongoDB - Ruby Midwest
Alex Sharp
 
MongoDB - Ruby document store that doesn't rhyme with ouch
Wynn Netherland
 
MongoDB Replication (Dwight Merriman)
MongoSF
 
Cosmic rays detection theory
Lalit Pradhan
 
Cosmic Ray Presentation
guest3aa2df
 
physics lecture
Jolie John Ej Cadag
 
MongoDB: How it Works
Mike Dirolf
 
Solid state physics - Crystalline Solids
Athren Tidalgo
 
Ad

Similar to Ruby Development and MongoMapper (John Nunemaker) (20)

PDF
Mongo and Harmony
Steve Smith
 
PDF
Mongoid in the real world
Kevin Faustino
 
PDF
Declarative Data Modeling in Python
Joshua Forman
 
PPTX
Rapid and Scalable Development with MongoDB, PyMongo, and Ming
Rick Copeland
 
PDF
Pyconie 2012
Yaqi Zhao
 
PDF
Tame Accidental Complexity with Ruby and MongoMapper
Giordano Scalzo
 
KEY
MongoDB & Mongoid with Rails
Justin Smestad
 
KEY
Inside PyMongo - MongoNYC
Mike Dirolf
 
PDF
"Use Component Drivers to Control Components in Tests", Roman Shevchuk
Fwdays
 
KEY
Python Development (MongoSF)
Mike Dirolf
 
PPTX
PyCon APAC - Django Test Driven Development
Tudor Munteanu
 
PPT
WEB DESIGNING VNSGU UNIT 4 JAVASCRIPT OBJECTS
divyapatel123440
 
PDF
Metaprogramovanie #1
Jano Suchal
 
KEY
MongoMapper lightning talk
Kerry Buckley
 
PDF
Separation of concerns - DPC12
Stephan Hochdörfer
 
PDF
Fun Teaching MongoDB New Tricks
MongoDB
 
PDF
Building Apps with MongoDB
Nate Abele
 
PPTX
DOM and Events
Julie Iskander
 
PDF
The Ring programming language version 1.5.1 book - Part 43 of 180
Mahmoud Samir Fayed
 
PDF
All you need to know about JavaScript Functions
Oluwaleke Fakorede
 
Mongo and Harmony
Steve Smith
 
Mongoid in the real world
Kevin Faustino
 
Declarative Data Modeling in Python
Joshua Forman
 
Rapid and Scalable Development with MongoDB, PyMongo, and Ming
Rick Copeland
 
Pyconie 2012
Yaqi Zhao
 
Tame Accidental Complexity with Ruby and MongoMapper
Giordano Scalzo
 
MongoDB & Mongoid with Rails
Justin Smestad
 
Inside PyMongo - MongoNYC
Mike Dirolf
 
"Use Component Drivers to Control Components in Tests", Roman Shevchuk
Fwdays
 
Python Development (MongoSF)
Mike Dirolf
 
PyCon APAC - Django Test Driven Development
Tudor Munteanu
 
WEB DESIGNING VNSGU UNIT 4 JAVASCRIPT OBJECTS
divyapatel123440
 
Metaprogramovanie #1
Jano Suchal
 
MongoMapper lightning talk
Kerry Buckley
 
Separation of concerns - DPC12
Stephan Hochdörfer
 
Fun Teaching MongoDB New Tricks
MongoDB
 
Building Apps with MongoDB
Nate Abele
 
DOM and Events
Julie Iskander
 
The Ring programming language version 1.5.1 book - Part 43 of 180
Mahmoud Samir Fayed
 
All you need to know about JavaScript Functions
Oluwaleke Fakorede
 
Ad

More from MongoSF (18)

PPTX
Webinar: Typische MongoDB Anwendungsfälle (Common MongoDB Use Cases) 
MongoSF
 
PPTX
Schema design with MongoDB (Dwight Merriman)
MongoSF
 
KEY
C# Development (Sam Corder)
MongoSF
 
KEY
Flexible Event Tracking (Paul Gebheim)
MongoSF
 
KEY
Administration (Eliot Horowitz)
MongoSF
 
KEY
Administration
MongoSF
 
KEY
Sharding with MongoDB (Eliot Horowitz)
MongoSF
 
KEY
Practical Ruby Projects (Alex Sharp)
MongoSF
 
PDF
Implementing MongoDB at Shutterfly (Kenny Gorman)
MongoSF
 
PDF
Debugging Ruby (Aman Gupta)
MongoSF
 
PPTX
Indexing and Query Optimizer (Aaron Staple)
MongoSF
 
PDF
Zero to Mongo in 60 Hours
MongoSF
 
KEY
Building a Mongo DSL in Scala at Hot Potato (Lincoln Hochberg)
MongoSF
 
KEY
PHP Development with MongoDB (Fitz Agard)
MongoSF
 
PPT
Java Development with MongoDB (James Williams)
MongoSF
 
PPTX
Real time ecommerce analytics with MongoDB at Gilt Groupe (Michael Bryzek & M...
MongoSF
 
PPTX
From MySQL to MongoDB at Wordnik (Tony Tam)
MongoSF
 
PDF
Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)
MongoSF
 
Webinar: Typische MongoDB Anwendungsfälle (Common MongoDB Use Cases) 
MongoSF
 
Schema design with MongoDB (Dwight Merriman)
MongoSF
 
C# Development (Sam Corder)
MongoSF
 
Flexible Event Tracking (Paul Gebheim)
MongoSF
 
Administration (Eliot Horowitz)
MongoSF
 
Administration
MongoSF
 
Sharding with MongoDB (Eliot Horowitz)
MongoSF
 
Practical Ruby Projects (Alex Sharp)
MongoSF
 
Implementing MongoDB at Shutterfly (Kenny Gorman)
MongoSF
 
Debugging Ruby (Aman Gupta)
MongoSF
 
Indexing and Query Optimizer (Aaron Staple)
MongoSF
 
Zero to Mongo in 60 Hours
MongoSF
 
Building a Mongo DSL in Scala at Hot Potato (Lincoln Hochberg)
MongoSF
 
PHP Development with MongoDB (Fitz Agard)
MongoSF
 
Java Development with MongoDB (James Williams)
MongoSF
 
Real time ecommerce analytics with MongoDB at Gilt Groupe (Michael Bryzek & M...
MongoSF
 
From MySQL to MongoDB at Wordnik (Tony Tam)
MongoSF
 
Map/reduce, geospatial indexing, and other cool features (Kristina Chodorow)
MongoSF
 

Recently uploaded (20)

PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
PPT
Ericsson LTE presentation SEMINAR 2010.ppt
npat3
 
PPTX
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
PDF
UiPath DevConnect 2025: Agentic Automation Community User Group Meeting
DianaGray10
 
PPTX
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
PDF
“Computer Vision at Sea: Automated Fish Tracking for Sustainable Fishing,” a ...
Edge AI and Vision Alliance
 
DOCX
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
PDF
The 2025 InfraRed Report - Redpoint Ventures
Razin Mustafiz
 
PPTX
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PDF
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PDF
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
PPTX
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
PDF
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
PDF
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
PDF
SIZING YOUR AIR CONDITIONER---A PRACTICAL GUIDE.pdf
Muhammad Rizwan Akram
 
PDF
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PDF
NASA A Researcher’s Guide to International Space Station : Physical Sciences ...
Dr. PANKAJ DHUSSA
 
PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
Ericsson LTE presentation SEMINAR 2010.ppt
npat3
 
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
UiPath DevConnect 2025: Agentic Automation Community User Group Meeting
DianaGray10
 
The Project Compass - GDG on Campus MSIT
dscmsitkol
 
“Computer Vision at Sea: Automated Fish Tracking for Sustainable Fishing,” a ...
Edge AI and Vision Alliance
 
Python coding for beginners !! Start now!#
Rajni Bhardwaj Grover
 
The 2025 InfraRed Report - Redpoint Ventures
Razin Mustafiz
 
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
SIZING YOUR AIR CONDITIONER---A PRACTICAL GUIDE.pdf
Muhammad Rizwan Akram
 
Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
NASA A Researcher’s Guide to International Space Station : Physical Sciences ...
Dr. PANKAJ DHUSSA
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 

Ruby Development and MongoMapper (John Nunemaker)