views:

286

answers:

3

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

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

Any idea if this has already been implemented, if it's going to be in rails 3.0 ?

+1  A: 

You won't see after_commit in Rails 3.0, at least not yet. You can apply a patch and see if it gets approved by the core team, but I doubt it would. This functionality remains much more functional outside of the Rails core, in a plugin.

You can try this plugin:

http://github.com/GUI/after_commit

Josh
I looked at the plugin, but it's a static way of defining after commits, and they are hooked on a single model from what I saw. I would prefere something that you add to the `after_commit` callbacks while saving.
Gaspard Bucher
A: 

I have created a lightweight after_commit plugin: after_commit plugin that enables the following syntax:

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

It's very lightweight but does the job.

Gaspard Bucher
A: 

This is in Rails core in Rails 3.

Documentation here: http://edgeapi.rubyonrails.org/classes/ActiveRecord/Transactions/ClassMethods.html#M001117

Nick Ragaz