Skip to content

brentmc79/without_callbacks

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

WithoutCallbacks
================

ActiveRecord callbacks can be extremely useful, but sometimes they 
just get in the way.  Wouldn't it be nice if you could disable the 
callbacks at will?  Well, now you can!



Example
=======

Given an AR model like so:

class ShamWowGuy < ActiveRecord::Base
	before_save :slap_chop
	before_update :punch_hooker
	private
		def punch_hooker
			self.hooker_count = hooker_count+1
		end
		def slap_chop
			self.catchphrase = "You're gonna love my nuts!"
		end
end

What happens when you create/save the model?

vince = ShamWowGuy.new(:catchphrase => "You'll say WOW every time!")
vince.save
vince.catchphrase #=> "You're gonna love my nuts!"

When the model is saved, its catchphrase attribute is updated by the
callback just prior to being persisted to the database.

Maybe your Mom came by for a visit and you don't really want Vince,
the ShamWow guy, blurting offensive comments about his nuts.  Well, 
here's what you do:

vince = ShamWowGuy.new(:catchphrase => "You'll say WOW evey time!")
ShamWowGuy.without_callbacks(:slap_chop) do
	vince.save
end
vince.catchphrase #=> "You'll say WOW evey time!"

Uh-oh, there's a typo in our catchphrase, so we need to update
vince.  Mom's still here and she doesn't approve of hooker-punching.
What's a girl to do?

We can pass in both callback method names, like so:

ShamWowGuy.without_callbacks(:slap_chop, :punch_hooker) do
	vince.save
end

Or, we can disable ALL callbacks by not passing any arguments:

ShamWowGuy.without_callbacks do
	vince.save
end

That's all there is to it!



Note
====

At the moment, without_callbacks only disables instance methods
defined within the specified class.  Procs or eval'd strings 
like this:

before_save {|sham_wow_guy| sham_wow_guy.slap_chop }

OR

before_update 'self.hooker_count = nil'

in the callback class methods are not yet handled.




Copyright (c) 2009 Brent Collier, released under the MIT license

About

A Ruby On Rails plugin that enables the temporary disabling of ActiveRecord callbacks

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Languages