class BSON::DBRef
Represents a DBRef document in the database.
def as_json(*args)
-
(Hash)
- The max key as a JSON hash.
Other tags:
- Example: Get the DBRef as a JSON hash. -
def as_json(*args) {}.update(self) end
def collection
-
(String)
- collection The collection name.
def collection self['$ref'] end
def database
-
(String)
- database The database name.
def database self['$db'] end
def id
-
(BSON::ObjectId)
- id The referenced document id.
def id self['$id'] end
def initialize(hash_or_collection, id = nil, database = nil)
-
(BSON::Error::InvalidDBRefArgument)
- if giving invalid arguments
Parameters:
-
database
(String
) -- The database name, when using the legacy API. -
id
(Object
) -- The object id, when using the legacy API. -
hash_or_collection
(Hash | String
) -- The DBRef hash, when using
Other tags:
- Example: Create the DBRef - legacy API. -
Example: Create the DBRef - hash API. -
def initialize(hash_or_collection, id = nil, database = nil) if hash_or_collection.is_a?(Hash) hash = hash_or_collection unless id.nil? && database.nil? raise Error::InvalidDBRefArgument, 'When using the hash API, DBRef constructor accepts only one argument' end else warn("BSON::DBRef constructor called with the legacy API - please use the hash API instead") if id.nil? raise Error::InvalidDBRefArgument, 'When using the legacy constructor API, id must be provided' end hash = { :$ref => hash_or_collection, :$id => id, :$db => database, } end hash = reorder_fields(hash) %w($ref $id).each do |key| unless hash[key] raise Error::InvalidDBRefArgument, "DBRef must have #{key}: #{hash}" end end unless hash['$ref'].is_a?(String) raise Error::InvalidDBRefArgument, "The value for key $ref must be a string, got: #{hash['$ref']}" end if db = hash['$db'] unless db.is_a?(String) raise Error::InvalidDBRefArgument, "The value for key $db must be a string, got: #{hash['$db']}" end end super(hash) end
def reorder_fields(hash)
-
(Hash)
- The hash with it's fields reordered.
Parameters:
-
hash
(Hash
) -- The input hash. Must be a valid dbref.
def reorder_fields(hash) hash = BSON::Document.new(hash) reordered = {} reordered['$ref'] = hash.delete('$ref') reordered['$id'] = hash.delete('$id') if db = hash.delete('$db') reordered['$db'] = db end reordered.update(hash) end
def to_bson(buffer = ByteBuffer.new)
-
(BSON::ByteBuffer)
- The buffer with the encoded object.
Parameters:
-
buffer
(BSON::ByteBuffer
) -- The encoded BSON buffer to append to.
Other tags:
- Example: Convert the DBRef to raw BSON. -
def to_bson(buffer = ByteBuffer.new) as_json.to_bson(buffer) end