forked from manveru/ramaze
-
Notifications
You must be signed in to change notification settings - Fork 37
Mongomapper
royw edited this page Aug 15, 2012
·
2 revisions
MongoMapper requires the mongodb be installed and running. Note this example is a little old, you probably want to use a newer version of mongomapper.
gem 'mongo', '~>1.3.0'
gem 'mongo_mapper', '~>0.9.0'
# Here goes your database connection and options:
require 'mongo_mapper'
require 'log4r'
# connect with a logger! Whoooop! Great feature
MongoMapper.connection = Mongo::Connection.new('localhost', nil, :logger => Log4r::Logger['charta'])
MongoMapper.database = 'charta-test'
# Use identity map for all models
module IdentityMapAddition
def self.included(model)
model.plugin MongoMapper::Plugins::IdentityMap
end
end
# our mongomapper extensions
Dir[__DIR__('extensions/*.rb')].each {|name| require name}
# Here go your requires for models:
require __DIR__('card')
This is an example for a custom data type, in this case an array constrained to unique values
module MongoMapper
module Extensions
module UniqArray
# to_mongo gets called anytime a value is assigned
def to_mongo(value)
value = value.respond_to?(:lines) ? value.lines : value
value.to_a.uniq
end
# from mongo gets called anytime a value is read
def from_mongo(value)
(value || []).uniq
end
end
end
end
class UniqArray
extend MongoMapper::Extensions::UniqArray
end
This is an example model.
# This models the 3x5 card with self referencing parents and children associations
class Card
include MongoMapper::Document
key :name, String
key :owner, User, :required => true
key :readers, Array, :typecast => 'User', :default => []
key :writers, Array, :typecast => 'User', :default => []
key :fields, Array, :default => []
key :card_ids, Array, :typecast => 'ObjectId', :default => []
many :children, :in => :card_ids, :class_name => 'Card'
key :parent_card_ids, Array, :typecast => 'ObjectId', :default => []
many :parents, :in => :parent_card_ids, :class_name => 'Card'
def children?
children.size > 0
end
def parents?
parents.size > 0
end
# Card attachment methods are self saving otherwise
# the bidirectional parent-to-childe relationships could be
# compromised.
def attach_parent(card)
parents << card
card.children << self
card.save
save
end
def attach_child(card)
children << card
card.parents << self
card.save
save
end
def detach_parent(card)
parents.delete(card)
card.children.delete(self)
card.save
save
end
def detach_child(card)
children.delete(card)
card.parents.delete(self)
card.save
save
end
end
- Website
- Google Groups
- User Guide
- [#ramaze on the Freenode network] (http://webchat.freenode.net/?channels=ramaze)