0.0
No commit activity in last 3 years
No release in over 3 years
mongo_persist
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
 Dependencies

Development

>= 1.0.0
>= 0
~> 1.8.4
>= 0
~> 3.12
>= 0
~> 2.8.0

Runtime

 Project Readme

MongoPersist¶ ↑

Library to add MongoDB Persistance to normal Ruby objects

Example¶ ↑

require 'rubygems'
require 'mongo'
require 'mongo_persist'

class Order
  include MongoPersist
  attr_accessor :po_number
  fattr(:order_products) { [] }
  def products
    order_products.map { |x| x.product }
  end
end

class OrderProduct
  include MongoPersist
  attr_accessor :unit_price, :quantity, :product

  # Store a reference to objects for this attribute, not the entire object.
  mongo_reference_attributes ['product']
end

class Product
  include MongoPersist
  attr_accessor :name
end

products = [Product.new(:name => 'Leather Couch'),Product.new(:name => 'Maroon Chair')].each { |x| x.mongo_save! }

orders = []
orders << Order.new(:po_number => 1234, :order_products => [OrderProduct.new(:unit_price => 1000, :quantity => 1, :product => products[0])]).mongo_save!
orders << Order.new(:po_number => 1235, :order_products => [OrderProduct.new(:unit_price => 200, :quantity => 2, :product => products[1])]).mongo_save!

# objects are saved to MongoDB as JSON objects

# get all order objects back from Mongo
# you get back the ruby objects you put in, not raw JSON objects
Order.collection.find_objects 

# Since on OrderProduct, the product attribute was marked as a reference attribute,
# the product is stored in MongoDB only as a reference to the product obj
#
# When you read the Order/OrderProduct back out, MongoPersist takes care of
# fetching the Product object again.  You don't have to do anything.
Order.collection.find_one_object.products.first # An object of class Product
Order.collection.find_one_object.products.first.name  # Leather Couch

# Because the product is stored as a reference, if you update that product
# elsewhere and save to Mongo, later reads of Orders with that product will be correctly updated
products[0].name = 'White Leather Couch'
products[0].mongo_save!
Order.collection.find_one_object.products.first.name  # White Leather Couch

Note on Patches/Pull Requests¶ ↑

  • Fork the project.

  • Make your feature addition or bug fix.

  • Add tests for it. This is important so I don’t break it in a future version unintentionally.

  • Commit, do not mess with rakefile, version, or history. (if you want to have your own version, that is fine but

    bump version in a commit by itself I can ignore when I pull)
  • Send me a pull request. Bonus points for topic branches.

Copyright © 2009 Mike Harris. See LICENSE for details.