阅读更多

5顶
0踩

编程语言

原创新闻 Mongomatic:映射Ruby对象到Mongodb

2010-08-17 15:57 by 副主编 just_cool 评论(2) 有3371人浏览

Mongomatic是一个Ruby库,可以映射Ruby对象到Mongodb文档数据库。目前最新版是0.3.1版本。


安装:

$ gem install mongomatic

Successfully installed mongomatic

1 gem installed

 

示例代码:

require 'rubygems'
require 'mongomatic'
 
Mongomatic.db = Mongo::Connection.new().db('test')
# Tip: You can also set User.db to a different Mongo::DB
 
class User < Mongomatic::Base
  def self.create_indexes
    self.collection.create_index("email", :unique => true)
    self.collection.create_index("friend_ids")
  end
 
  def add_friend(user)
    self.push("friend_ids", user["_id"])
  end
 
  def remove_friend(user)
    self.pull("friend_ids", user["_id"])
  end
 
  def friends
    # Returns a Mongomatic::Cursor that wraps a Mongo::Cursor
    User.find( { "_id" => { "$in" => (self["friend_ids"] || []) } } )
  end
 
  def friended_by
    # Returns a Mongomatic::Cursor that wraps a Mongo::Cursor
    User.find( { "friend_ids" => self["_id"] } )
  end
 
  protected
 
  def validate
    self.errors << ["email", "is blank"] if self["email"].blank?
    self.errors << ["address.zip", "is blank"] if (self["address"] || {})["zip"].blank?
  end
 
  def before_insert
    self["inserted_at"] = Time.now.utc
  end
 
  def before_update
    self["updated_at"] = Time.now.utc
  end
end
 

点击查看详情:http://mongomatic.com/

  • 大小: 52.2 KB
5
0
评论 共 2 条 请登录后发表评论
2 楼 agile_boy 2010-08-18 11:37
mongoid也是不错的选择哦
1 楼 googya 2010-08-18 09:29
好东西是越来越多了

发表评论

您还没有登录,请您登录后再发表评论

相关推荐

Global site tag (gtag.js) - Google Analytics