From ae5d839fb765a1292b02f7448fee18c9be43ca10 Mon Sep 17 00:00:00 2001 From: Durran Jordan Date: Fri, 18 Dec 2009 19:55:42 -0500 Subject: [PATCH] Allow passing of block to Document#initialize --- lib/mongoid/document.rb | 3 ++- spec/unit/mongoid/document_spec.rb | 13 +++++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/lib/mongoid/document.rb b/lib/mongoid/document.rb index 481d81b221..1dbb5d833a 100644 --- a/lib/mongoid/document.rb +++ b/lib/mongoid/document.rb @@ -181,7 +181,8 @@ def initialize(attrs = {}) @attributes = {}.with_indifferent_access process(defaults.merge(attrs)) @new_record = true if id.nil? - generate_key + document = yield self if block_given? + generate_key; document end # Returns the class name plus its attributes. diff --git a/spec/unit/mongoid/document_spec.rb b/spec/unit/mongoid/document_spec.rb index 2b16dd243a..98902eb347 100644 --- a/spec/unit/mongoid/document_spec.rb +++ b/spec/unit/mongoid/document_spec.rb @@ -338,6 +338,19 @@ describe "#new" do + context "when passed a block" do + + it "yields self to the block" do + person = Person.new do |p| + p.title = "Sir" + p.age = 60 + end + person.title.should == "Sir" + person.age.should == 60 + end + + end + context "with no attributes" do it "sets default attributes" do