Sha256: 8789992d401bf501828ad6e1b41b754a1f52982215d664033f52e227dddaebd9

Contents?: true

Size: 993 Bytes

Versions: 2

Compression:

Stored size: 993 Bytes

Contents

module MongoHash
  def get_mongo_id
    ['_id','mongo_id'].each { |x| return self[x] if self[x] }
    nil
  end
  def naked_reference?
    (keys - ['_id','_mongo_class','mongo_id']).empty? && !!get_mongo_id
  end
  def mongo_class
    self['_mongo_class'] ? eval(self['_mongo_class']) : nil
  end
  def to_mongo_hash_for_obj
    h = reject { |k,v| k == '_mongo_class' }
    h['mongo_id'] = h['_id'] if h['_id']
    h.reject { |k,v| k == '_id' }
  end
  def to_mongo_object
    return map_value { |v| v.safe_to_mongo_object }.map_key { |k| k.from_mongo_key } unless mongo_class
    if naked_reference?
      mongo_class.collection.find_one_object('_id' => get_mongo_id)
    else
      mongo_class.from_mongo_hash(to_mongo_hash_for_obj)
    end
  end
  def to_mongo_hash
    res = {}
    each { |k,v| res[k.safe_to_mongo_hash.to_mongo_key] = v.safe_to_mongo_hash }
    res
  end

  def can_mongo_convert?
    all? { |k,x| x.can_mongo_convert? && x }
  end
end

class Hash
  include MongoHash
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
mongo_persist-0.2.1 lib/mongo_persist/hash_ext.rb
mongo_persist-0.2.0 lib/mongo_persist/hash_ext.rb