Created
December 22, 2010 07:53
-
-
Save coffeeaddict/751245 to your computer and use it in GitHub Desktop.
Kijk mama! Ik heb een infinite loop gemaakt!
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# ... | |
def sema_key; "stock-observer-semaphores"; end | |
# make sure the stock off all coupled products is always equal | |
def update_coupled_stock(stock) | |
# get the current list of semaphores | |
semaphores = Rails.cache.read(sema_key) || [] | |
# when this stocks is already being updated, leave now | |
return if semaphores.include? stock.id | |
# update the list of semaphores | |
Rails.cache.write(sema_key, semaphores << stock.id ) | |
attributes = { | |
:stock => stock.stock, | |
:min => stock.min, | |
:max => stock.max, | |
:active => stock.active | |
} | |
unless stock.coupled_stocks.empty? | |
stock.coupled_stocks.each do |coupled| | |
Rails.logger.info "Updating coupled stock: #{coupled.product}" | |
coupled.update_attributes( attributes ) | |
end | |
end | |
unless stock.coupled_to.nil? | |
stock.coupled_to.update_attributes( attributes ) | |
end | |
# now that we're done, the semaphore can be removed | |
semaphores = Rails.cache.read(sema_key) | |
semaphores.delete stock.id | |
# rewrite the list of semaphores | |
Rails.cache.write(sema_key, semaphores) | |
end | |
# ... |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class StockObserver < ActiveRecord::Observer | |
observe :stock | |
# ... | |
# make sure the stock off all coupled products is always equal | |
def update_coupled_stock(stock) | |
attributes = { | |
:stock => stock.stock, | |
:min => stock.min, | |
:max => stock.max, | |
:active => stock.active | |
} | |
unless stock.coupled_stocks.empty? | |
stock.coupled_stocks.each do |coupled| | |
Rails.logger.info "Updating coupled stock: #{coupled.product}" | |
coupled.update_attributes( attributes ) | |
end | |
end | |
unless stock.coupled_to.nil? | |
stock.coupled_to.update_attributes( attributes ) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment