Skip to content

Commit

Permalink
Refactoring to eliminate callback loops
Browse files Browse the repository at this point in the history
  • Loading branch information
Denis 'jumph4x authored and romul committed Apr 8, 2012
1 parent 5ab104d commit aba3def
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 4 deletions.
11 changes: 10 additions & 1 deletion app/models/core_charge.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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?
Expand All @@ -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
21 changes: 18 additions & 3 deletions lib/spree_core_charges.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down

0 comments on commit aba3def

Please sign in to comment.