Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 11 additions & 6 deletions lib/bson.rb
Original file line number Diff line number Diff line change
Expand Up @@ -21,20 +21,25 @@
# @since 0.0.0
module BSON

# Create a new object id from a string using ObjectId.from_string
# Interprets the argument as an ObjectId. If given a BSON::ObjectId, this method
# returns it directly without creating a new one. Otherwise, the argument is
# interpreted as a string and parsed accordingly.
#
# @example Create an object id from the string.
# BSON::ObjectId(id)
# BSON::ObjectId('...')
#
# @param [ String ] string The string to create the id from.
# @param [ String | BSON::ObjectId ] string_or_object_id The string to create the id from,
# or the existing object id to return.
#
# @raise [ BSON::Error::InvalidObjectId ] If the provided string is invalid.
#
# @return [ BSON::ObjectId ] The new object id.
# @return [ BSON::ObjectId ] The new or existing object id.
#
# @see ObjectId.from_string
def self.ObjectId(string)
self::ObjectId.from_string(string)
def self.ObjectId(string_or_object_id)
return string_or_object_id if string_or_object_id.is_a?(self::ObjectId)

self::ObjectId.from_string(string_or_object_id)
end

# Constant for binary string encoding.
Expand Down
20 changes: 16 additions & 4 deletions spec/bson_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,23 @@

describe ".ObjectId" do

let(:string) { "4e4d66343b39b68407000001" }
context 'when given a string' do
let(:string) { "4e4d66343b39b68407000001" }

it "returns an BSON::ObjectId from given string" do
expect(described_class::ObjectId(string)).to be_a BSON::ObjectId
expect(described_class::ObjectId(string)).to eq BSON::ObjectId.from_string(string)
it "returns a BSON::ObjectId from given string" do
expect(described_class::ObjectId(string)).to be_a BSON::ObjectId
expect(described_class::ObjectId(string)).to eq BSON::ObjectId.from_string(string)
end
end

context 'when given an object id' do
let(:object_id) do
described_class::ObjectId.new
end

it 'returns the same object' do
expect(described_class::ObjectId(object_id)).to be(object_id)
end
end
end

Expand Down
Loading