发表于 2015-7-9 12:35:46

Ruby在使用MongoDB时,对Cursor的重新包装

  MongoDB是个好东西,作为非关系数据库,十分的便利,符合Ruby的一贯精神
  在使用中,出现了以下问题:
  调用 DB.collection.find(...) 返回的对象是 Cursor,而Cursor#each 或 Cursor#next_document ... 的对象是OrderedHash
  我们难免会设计数据库层来简化数据库通讯,我们设定以下语境来描述这个问题:
  

class Sample
...
def self.find(hash = nil)
cursor = self.collection.find(hash)
cursor
end
def self.to_sample(ordered_hash)
...
end
...
end
  Sample 对应于一个Collection,Sample#find返回一个cursor,而我们使用的方法大致如下:
  

Sample.find.each |hash|
sample = Sample.to_sample(hash)
...
end

  这是段极其Ugly的代码,每次我们从Sample#find获得的对象都要 to_sample一下才能使用,不得不考虑Ruby强大解决能力:
  

class Sample
...
def initialize(ordered_hash)
...
end
#instead of :
#def self.to_sample(ordered_hash)
#...
#end
def self.find(hash = nil)
cursor = self.collection.find(hash)
class
页: [1]
查看完整版本: Ruby在使用MongoDB时,对Cursor的重新包装