Permalink
Browse files

fix after_initialize edge case (close #2074 and close #2175)

fix behavior when after_initialize is defined and a block is passed to Base.create
  • Loading branch information...
1 parent 6f917ad commit 3dc5f71c1757ffd3f949162807635c0f884118a6 @hmcfletch hmcfletch committed with cldwalker Jul 21, 2011
@@ -505,8 +505,7 @@ def create(attributes = nil, options = {}, &block)
if attributes.is_a?(Array)
attributes.collect { |attr| create(attr, options, &block) }
else
- object = new(attributes, options)
- yield(object) if block_given?
+ object = new(attributes, options, &block)
object.save
object
end
@@ -21,6 +21,7 @@
require 'models/person'
require 'models/edge'
require 'models/joke'
+require 'models/wholesale_product'
require 'rexml/document'
require 'active_support/core_ext/exception'
@@ -250,6 +251,28 @@ def test_initialize_with_invalid_attribute
end
end
+ def test_create_with_after_initialize
+ wp1 = WholesaleProduct.create(:msrp => 10)
+ assert_equal(10, wp1.msrp)
+ assert_equal(5, wp1.wholesale)
+
+ wp2 = WholesaleProduct.create(:wholesale => 10)
+ assert_equal(20, wp2.msrp)
+ assert_equal(10, wp2.wholesale)
+
+ wp3 = WholesaleProduct.create do |wp|
+ wp.msrp = 10
+ end
+ assert_equal(10, wp3.msrp)
+ assert_equal(5, wp3.wholesale)
+
+ wp4 = WholesaleProduct.create do |wp|
+ wp.wholesale = 10
+ end
+ assert_equal(20, wp4.msrp)
+ assert_equal(10, wp4.wholesale)
+ end
+
def test_load
topics = Topic.find(:all, :order => 'id')
assert_equal(4, topics.size)
@@ -0,0 +1,13 @@
+class WholesaleProduct < ActiveRecord::Base
+
+ after_initialize :set_prices
+
+ def set_prices
+ if msrp.nil? && !wholesale.nil?
+ self.msrp = 2 * wholesale
+ elsif !msrp.nil? && wholesale.nil?
+ self.wholesale = msrp / 2
+ end
+ end
+
+end
@@ -676,6 +676,11 @@ def create_table(*args, &block)
t.references :wheelable, :polymorphic => true
end
+ create_table :wholesale_products, :force => true do |t|
+ t.integer :msrp
+ t.integer :wholesale
+ end
+
create_table :zines, :force => true do |t|
t.string :title
end

0 comments on commit 3dc5f71

Please sign in to comment.