From c9d2611bb7bd09b0ed7e8962d0f578f841d17b40 Mon Sep 17 00:00:00 2001 From: Peter Williams Date: Wed, 11 May 2011 13:53:28 -0600 Subject: [PATCH] Support providing an initialization block when creating new models --- lib/couchrest/model/base.rb | 4 ++++ spec/couchrest/base_spec.rb | 5 +++++ 2 files changed, 9 insertions(+) diff --git a/lib/couchrest/model/base.rb b/lib/couchrest/model/base.rb index 0f6d26c..5f3a6cd 100644 --- a/lib/couchrest/model/base.rb +++ b/lib/couchrest/model/base.rb @@ -49,6 +49,8 @@ module CouchRest # * :directly_set_attributes: true when data comes directly from database # * :database: provide an alternative database # + # If a block is provided the new model will be passed into the + # block so that it can be populated. def initialize(doc = {}, options = {}) doc = prepare_all_attributes(doc, options) # set the instances database, if provided @@ -57,6 +59,8 @@ module CouchRest unless self['_id'] && self['_rev'] self[self.model_type_key] = self.class.to_s end + yield self if block_given? + after_initialize if respond_to?(:after_initialize) end diff --git a/spec/couchrest/base_spec.rb b/spec/couchrest/base_spec.rb index 21c9a40..208d6e7 100644 --- a/spec/couchrest/base_spec.rb +++ b/spec/couchrest/base_spec.rb @@ -44,6 +44,11 @@ describe "Model Base" do @obj.database.should eql('database') end + it "should support initialization block" do + @obj = Basic.new {|b| b.database = 'database'} + @obj.database.should eql('database') + end + end describe "ActiveModel compatability Basic" do