From 421ceb10902e258e7f509b33d3d3b855616a1eb6 Mon Sep 17 00:00:00 2001 From: Durran Jordan Date: Sun, 13 May 2012 11:55:54 +0200 Subject: [PATCH] Add Moped::BSON.ObjectId(string) - For compatibility with apps that may use the 10gen driver API with regards to creating object ids from strings. - No inspection override here. - Closes #4. --- lib/moped/bson.rb | 17 ++++++++++++++ spec/moped/bson_spec.rb | 52 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 69 insertions(+) create mode 100644 spec/moped/bson_spec.rb diff --git a/lib/moped/bson.rb b/lib/moped/bson.rb index 46a26f7..1d25c0e 100644 --- a/lib/moped/bson.rb +++ b/lib/moped/bson.rb @@ -21,5 +21,22 @@ module BSON FLOAT_PACK = 'E'.freeze START_LENGTH = [0].pack(INT32_PACK).freeze + + class << self + + # Create a new object id from the provided string. + # + # @example Create a new object id. + # Moped::BSON::ObjectId("4faf83c7dbf89b7b29000001") + # + # @param [ String ] string The string to use. + # + # @return [ ObjectId ] The object id. + # + # @since 1.0.0 + def ObjectId(string) + ObjectId.from_string(string) + end + end end end diff --git a/spec/moped/bson_spec.rb b/spec/moped/bson_spec.rb new file mode 100644 index 0000000..b00795b --- /dev/null +++ b/spec/moped/bson_spec.rb @@ -0,0 +1,52 @@ +require "spec_helper" + +describe Moped::BSON do + + describe ".ObjectId" do + + context "when provided a string" do + + context "when the string is a valid id" do + + let(:id) do + described_class.ObjectId("4faf83c7dbf89b7b29000001") + end + + let(:expected) do + Moped::BSON::ObjectId.from_string("4faf83c7dbf89b7b29000001") + end + + it "returns an object id" do + id.should eq(expected) + end + end + + context "when the string is not a valid id" do + + it "raises an error" do + expect { + described_class.ObjectId("test") + }.to raise_error(Moped::Errors::InvalidObjectId) + end + end + end + + context "when provided a non string" do + + it "raises an error" do + expect { + described_class.ObjectId(1) + }.to raise_error + end + end + + context "when provided nil" do + + it "raises an error" do + expect { + described_class.ObjectId(nil) + }.to raise_error + end + end + end +end