From d71f7d4e3a441c5577dfed0faf98957ff780325f Mon Sep 17 00:00:00 2001 From: Kyle Banker Date: Fri, 22 Jan 2010 14:56:00 -0500 Subject: [PATCH] support MongoDB extended JSON on ObjectID#to_json --- lib/mongo/types/objectid.rb | 8 ++++++-- test/test_objectid.rb | 2 +- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/lib/mongo/types/objectid.rb b/lib/mongo/types/objectid.rb index fad5f8d..a89fcc5 100644 --- a/lib/mongo/types/objectid.rb +++ b/lib/mongo/types/objectid.rb @@ -142,8 +142,12 @@ module Mongo end alias_method :inspect, :to_s - def to_json(*args) - %Q("#{to_s}") + # Convert to MongoDB extended JSON format. Since JSON includes type information, + # but lacks an ObjectID type, this JSON format encodes the type using an $id key. + # + # @return [String] the object id represented as MongoDB extended JSON. + def to_json(escaped=false) + "{\"$oid\": \"#{to_s}\"}" end # @deprecated diff --git a/test/test_objectid.rb b/test/test_objectid.rb index 5e49877..3156937 100644 --- a/test/test_objectid.rb +++ b/test/test_objectid.rb @@ -151,6 +151,6 @@ class ObjectIDTest < Test::Unit::TestCase def test_json id = ObjectID.new - assert_equal %Q("#{id}"), id.to_json + assert_equal "{\"$oid\": \"#{id}\"}", id.to_json end end