From aba3def7c5ada936bcb28b83e115e25c0731e4f1 Mon Sep 17 00:00:00 2001 From: Denis 'jumph4x Date: Mon, 12 Dec 2011 12:07:21 -0500 Subject: [PATCH] Refactoring to eliminate callback loops --- app/models/core_charge.rb | 11 ++++++++++- lib/spree_core_charges.rb | 21 ++++++++++++++++++--- 2 files changed, 28 insertions(+), 4 deletions(-) diff --git a/app/models/core_charge.rb b/app/models/core_charge.rb index f2f615e..4d7b509 100644 --- a/app/models/core_charge.rb +++ b/app/models/core_charge.rb @@ -4,6 +4,9 @@ class CoreCharge < ::Adjustment before_validation :set_amount + after_save :update_order + after_destroy :update_order + # We check if core charges even apply to this order # For this we see if any associated products have their core amounts set def applicable? @@ -17,7 +20,13 @@ def update! # Calculates core charges by summing relevant ones def set_amount - self.amount = source.variant.product.core_amount * source.quantity + self.amount ||= source.variant.product.core_amount * source.quantity end +private + + def update_order + order.update! + end + end diff --git a/lib/spree_core_charges.rb b/lib/spree_core_charges.rb index 004c039..643f567 100644 --- a/lib/spree_core_charges.rb +++ b/lib/spree_core_charges.rb @@ -40,19 +40,34 @@ def calculate_core_charge private def create_core_charges + CoreCharge.skip_callback :save, :after, :update_order + line_items(true).collect{|item| item if item.variant.product.core_amount }.compact.each do |item| - adjustments << Adjustment.create({ + adjustments << CoreCharge.create({ :label => I18n.t(:core_charge) + " [#{item.variant.sku || item.variant.name}]", :source => item, :order => self, :originator => item, :amount => item.calculate_core_charge - }) unless core_charges.find(:first, :conditions => {:source_id => item.id}) + }) unless core_charges.find(:first, :conditions => {:source_id => item.id, :originator_id => item.id}) end + + CoreCharge.set_callback :save, :after, :update_order + + self.update! end end - + + methodz = CoreCharge._save_callbacks.select{|c| c.raw_filter.class == Symbol} + CoreCharge.reset_callbacks :save + + methodz.each do |methud| + CoreCharge.set_callback :save, methud.kind, methud.raw_filter + end + + + end config.autoload_paths += %W(#{config.root}/lib)