Skip to content
Browse files

Modify run_after_commit to accept blocks

  • Loading branch information...
1 parent fcec94b commit ca3b912800cac4d4ea5b5d515075c57e5b441e98 @tism tism committed Jul 26, 2012
Showing with 27 additions and 5 deletions.
  1. +5 −4 lib/after_commit_queue.rb
  2. +12 −0 test/after_commit_queue_test.rb
  3. +10 −1 test/dummy/app/models/server.rb
View
9 lib/after_commit_queue.rb
@@ -10,15 +10,16 @@ module AfterCommitQueue
# Protected: Is called as after_commit callback
# runs methods from the queue and clears the queue afterwards
def _run_after_commit_queue
- _after_commit_queue.each do |method|
- send(method)
+ _after_commit_queue.each do |action|
+ action.call
end
@after_commit_queue.clear
end
# Protected: Add method to after commit queue
- def run_after_commit(method)
- _after_commit_queue << method
+ def run_after_commit(method = nil, &block)
+ _after_commit_queue << Proc.new { self.send(method) } if method
+ _after_commit_queue << block if block
@zbelzer
zbelzer added a note Jul 26, 2012

Why block instead of block_given?

@tism
tism added a note Jul 27, 2012

@zbelzer the block is already bound so if block vs if block_given? is much of a muchness

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
true
end
View
12 test/after_commit_queue_test.rb
@@ -16,6 +16,18 @@ def setup
assert @server.started
end
+ test "run blocks after transaction is committed" do
+ @server.start!
+ assert !@server.meditating
+
+ @server.transaction do
+ @server.crash!
+ assert !@server.meditating
+ end
+
+ assert @server.meditating
+ end
+
test "clear queue after methods from are called" do
@server.start!
@server.started = false
View
11 test/dummy/app/models/server.rb
@@ -1,13 +1,16 @@
class Server < ActiveRecord::Base
include AfterCommitQueue
- attr_accessor :started, :stopped
+ attr_accessor :started, :stopped, :meditating
state_machine :state, :initial => :pending do
after_transition :pending => :running, :do => :schedule_start
+ after_transition :running => :crashed, :do => :schedule_guru_meditation
after_transition :running => :turned_off, :do => :schedule_stop
+
event(:start) { transition :pending => :running }
event(:stop) { transition :running => :turned_off }
+ event(:crash) { transition :running => :crashed }
end
def schedule_start
@@ -18,6 +21,12 @@ def schedule_stop
run_after_commit(:stop_server)
end
+ def schedule_guru_meditation
+ run_after_commit do
+ @meditating = true
+ end
+ end
+
def start_server; @started = true end
def stop_server; @stopped = true end
end

0 comments on commit ca3b912

Please sign in to comment.
Something went wrong with that request. Please try again.