Skip to content

Commit

Permalink
Only use type in inheritance situations.
Browse files Browse the repository at this point in the history
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
durran committed Sep 9, 2012
1 parent f6dbc1c commit 36d0ba9
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 3 deletions.
1 change: 0 additions & 1 deletion lib/mongoid/fields.rb
Expand Up @@ -21,7 +21,6 @@ module Fields
self.pre_processed_defaults = [] self.pre_processed_defaults = []
self.post_processed_defaults = [] self.post_processed_defaults = []


field(:_type, default: ->{ self.class.name if hereditary? }, type: String)
field( field(
:_id, :_id,
default: ->{ Moped::BSON::ObjectId.new }, default: ->{ Moped::BSON::ObjectId.new },
Expand Down
7 changes: 7 additions & 0 deletions lib/mongoid/hierarchy.rb
Expand Up @@ -145,6 +145,13 @@ def inherited(subclass)
subclass.pre_processed_defaults = pre_processed_defaults.dup subclass.pre_processed_defaults = pre_processed_defaults.dup
subclass.post_processed_defaults = post_processed_defaults.dup subclass.post_processed_defaults = post_processed_defaults.dup
subclass.scopes = scopes.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 end
end end
Expand Down
4 changes: 2 additions & 2 deletions spec/mongoid/fields_spec.rb
Expand Up @@ -634,7 +634,7 @@
end end


it "does not return subclass defaults" do 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
end end


Expand All @@ -645,7 +645,7 @@
end end


it "has the parent and child defaults" do 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 end
end end
Expand Down

0 comments on commit 36d0ba9

Please sign in to comment.