diff --git a/lib/bson.rb b/lib/bson.rb index 15a54f373..4e5b7f778 100644 --- a/lib/bson.rb +++ b/lib/bson.rb @@ -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. diff --git a/spec/bson_spec.rb b/spec/bson_spec.rb index d849b7158..3f304d173 100644 --- a/spec/bson_spec.rb +++ b/spec/bson_spec.rb @@ -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