Rails after_commit?

Has anyone implemented an after_commit hook in Rails? I'm not looking for a model based on commits on update / create / etc, I want to be able to dynamically determine the block that will be executed only if the current (topmost) transaction passes:

 def remove_file current_transaction.after_commit do FileUtils.rm(file_path) end end 

Any idea if this is already implemented if it will be in rails 3.0?

+6
ruby-on-rails transactions
source share
5 answers

Rails 3 provides after_commit / after_rollback callbacks: https://github.com/rails/rails/commit/da840d13da865331297d5287391231b1ed39721b

In Rails 1 and 2, you can get the same functionality using this gem: https://github.com/freelancing-god/after_commit

+6
source share
+3
source share

In Rails 3.0, you will not see after_commit , at least not yet. You can apply the patch and see if it will be approved by the core team, but I doubt it will happen. This functionality remains much more functional outside the Rails core, in the plugin.

You can try this plugin:

http://github.com/GUI/after_commit

+2
source share

I created a lightweight after_commit plugin: an after_commit plugin that allows you to use the following syntax:

 def some_callback after_commit do # save file, expire cache, etc end end 

It is very light, but does the job.

+1
source share

Since the OP asked a question about how to dynamically configure the code that will be executed after the transaction, after_commit does not solve the problem. Fortunately, there is an after_commit_queue gem that solves exactly this problem.

Using the OP example, the code would look like this:

 include AfterCommitQueue def remove_file run_after_commit do FileUtils.rm(file_path) end end 
+1
source share

All Articles