Permalink
Browse files

Only use type in inheritance situations.

This is mostly a performance related change, but instead of always
having _type field defined and suffering the inheritance check every
time we apply defaults, we now only define it once something has been
subclassed.

The perf implications on 150k iterations:

Before:

Load from DB  4.580000   0.010000   4.590000 (  4.660224)
Instantiation 4.900000   0.000000   4.900000 (  4.904462)

After:

Load from DB  2.840000   0.010000   2.850000 (  2.910107)
Instantiation 3.540000   0.000000   3.540000 (  3.542787)
  • Loading branch information...
1 parent f6dbc1c commit 36d0ba9207ecf38b069a0a594c32da4803d6a234 @durran durran committed Sep 9, 2012
Showing with 9 additions and 3 deletions.
  1. +0 −1 lib/mongoid/fields.rb
  2. +7 −0 lib/mongoid/hierarchy.rb
  3. +2 −2 spec/mongoid/fields_spec.rb
View
@@ -21,7 +21,6 @@ module Fields
self.pre_processed_defaults = []
self.post_processed_defaults = []
- field(:_type, default: ->{ self.class.name if hereditary? }, type: String)
field(
:_id,
default: ->{ Moped::BSON::ObjectId.new },
View
@@ -145,6 +145,13 @@ def inherited(subclass)
subclass.pre_processed_defaults = pre_processed_defaults.dup
subclass.post_processed_defaults = post_processed_defaults.dup
subclass.scopes = scopes.dup
+
+ # We only need the _type field if inheritance is in play, but need to
+ # add to the root class as well for backwards compatibility.
+ unless fields.has_key?("_type")
+ field(:_type, default: self.name, type: String)
+ end
+ subclass.field(:_type, default: subclass.name, type: String)
end
end
end
@@ -634,7 +634,7 @@
end
it "does not return subclass defaults" do
- shape.pre_processed_defaults.should eq([ "_id", "x", "y" ])
+ shape.pre_processed_defaults.should eq([ "_id", "x", "y", "_type" ])
end
end
@@ -645,7 +645,7 @@
end
it "has the parent and child defaults" do
- circle.pre_processed_defaults.should eq([ "_id", "x", "y", "radius" ])
+ circle.pre_processed_defaults.should eq([ "_id", "x", "y", "_type", "radius" ])
end
end
end

0 comments on commit 36d0ba9

Please sign in to comment.