Skip to content

Commit

Permalink
BSON::ObjectId#inspect returns a string that evals into an object id
Browse files Browse the repository at this point in the history
`BSON::ObjectId('559acc9e546f6e09418d0200')` will now pass the
given string to BSON::ObjectId.from_string and return an equivalent
object id.

This change will allow for copying and pasting object ids without
having to use `#to_s` and `.from_string`, which would be nice when
working between different terminals
  • Loading branch information
tonyta committed Jul 6, 2015
1 parent fb73fb8 commit 5720474
Show file tree
Hide file tree
Showing 4 changed files with 32 additions and 2 deletions.
16 changes: 16 additions & 0 deletions lib/bson.rb
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,22 @@
# @since 0.0.0
module BSON

# Create a new object id from a string using ObjectId.from_string
#
# @example Create an object id from the string.
# BSON::ObjectId(id)
#
# @param [ String ] string The string to create the id from.
#
# @raise [ BSON::ObjectId::Invalid ] If the provided string is invalid.
#
# @return [ BSON::ObjectId ] The new object id.
#
# @see ObjectId.from_string
def self.ObjectId(string)
self::ObjectId.from_string(string)
end

# Constant for binary string encoding.
#
# @since 2.0.0
Expand Down
2 changes: 1 addition & 1 deletion lib/bson/object_id.rb
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ def hash
#
# @since 2.0.0
def inspect
"<BSON::ObjectId:0x#{object_id} data=#{to_s}>"
"BSON::ObjectId('#{to_s}')"
end

# Dump the raw bson when calling Marshal.dump.
Expand Down
6 changes: 5 additions & 1 deletion spec/bson/object_id_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -390,7 +390,11 @@
end

it "returns the inspection with the object id to_s" do
expect(object_id.inspect).to eq("<BSON::ObjectId:0x#{object_id.object_id} data=#{object_id.to_s}>")
expect(object_id.inspect).to eq("BSON::ObjectId('#{object_id.to_s}')")
end

it "returns a string that evaluates into an equivalent object id" do
expect(eval object_id.inspect).to eq object_id
end
end

Expand Down
10 changes: 10 additions & 0 deletions spec/bson_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,16 @@

describe BSON do

describe ".ObjectId" 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)
end
end

describe "::BINARY" do

it "returns BINARY" do
Expand Down

0 comments on commit 5720474

Please sign in to comment.