MongoDB is a document-oriented database that offers dynamic queries, fast updates, and schemaless design. It can scale horizontally and is suitable for most websites and caching applications. MongoDB uses MongoMapper for object-relational mapping with Ruby, allowing developers to define schemas and relationships between documents. Documents can be embedded within other documents to reduce joins and optimize performance.
20. CUSTOM DATATYPES
class Keywords class Presenter
def initialize(array) include MongoMapper::Document
@words = array key :keywords, Keywords
end end
def to_a
@words
end
class << self
def to_mongo(value)
value.is_a?(Keyword) ? keyword.to_a : value
end
def from_mongo(value)
value ? self.new(value) : nil
end
end
end
23. INHERITANCE
class Page class BlogPost < Page
key :permalink, String key :content, String
key :title, String has_many :comments
end end
class Redirect < Page
key :destination, String
end
24. MODULAR
module Authentication
def self.included(base)
base.key :password, String
base.key :salt, String
base.key :login, String
end
end
class Person
include MongoMapper::Document
include Authentication
end
26. ORDERS AS A DOCUMENT
class Order
include MongoMapper::Document
key :order_id, String
class << self
def for_site(site)
klass = Class.new(self)
klass.order_fields = site.order_fields
Object.const_set("OrderForSite#{site.id}", klass)
klass
end
def order_fields=(fields)
fields.each do |field|
key field, String
end
end
end
end
27. ORDERS: MONGOMAPPER
class Order
include MongoMapper::Document
key :order_id, String
28. ORDER: CLASS FOR A SPECIFIC
SITE
def for_site(site)
klass = Class.new(self)
klass.order_fields = site.order_fields
Object.const_set("OrderForSite#{site.id}", klass)
klass
end
29. DYNAMIC DOCUMENT
BUILDING
def order_fields=(fields)
fields.each do |field|
key field, String
end
end
30. PER USER
class Order
include MongoMapper::Document
key :order_id, String
class << self
def for_site(site)
klass = Class.new(self)
klass.order_fields = site.order_fields
Object.const_set("OrderForSite#{site.id}", klass)
klass
end
def order_fields=(fields)
fields.each do |field|
key field, String
end
end
end
end
31. SITE
• Can be a Mongo-document
• Can be an ActiveRecord object
• Can be a (Rails 3) ActiveModel object (REST?)
• Has to “respond_to? :id” and “respond_to? :order_fields”
32. TRY IT OUT
current_site.order_fields
#=> [“field1”, “field2”]
@order = Order.for_site(current_site).new
#=> #<OrderForSite2172858380 field1: nil, field2: nil,
order_id: nil>