Class: ActiveRecord::Reactor
- Inherits:
-
Object
- Object
- ActiveRecord::Reactor
- Includes:
- Singleton
- Defined in:
- lib/active_record/reactor.rb,
lib/active_record/reactor/version.rb,
lib/active_record/reactor/callbacks.rb
Overview
Active Record Reactors
ActiveRecord Reactors provide a defined way to react on default or custom ActiveRecord::Callbacks
. You may think of a Reactor as an Observer
which is explicitly registered with one or more models, and does not define any magic methods.
When a Reactor is registered with a model, it checks which of the model’s callbacks are also defined as reactor instance methods, and adds these to the model’s callback chain.
Reactor callbacks will always return true
, therefore it is not possible to halt the callback chain from a reactor. If you want to do that, you should consider moving the code inside the model.
Examples:
class YummyReactor < ActiveRecord::Reactor
after_create(record)
puts "Yummy, #{record.color} #{record.class.name} created!" if record.is_a?(Fruit)
end
end
class Fruit < ActiveRecord::Base
attr_accessor :peel
# Connect your model to the reactor
reactor :yummy
def color; end
end
Reactor scramming
Reactors can be halted temporarily using the scram
class method.
class Apple < Fruit; end
YummyReactor.scram do
Apple.create! # do not trigger reaction on YummyReactor
end
Defined Under Namespace
Modules: Callbacks
Constant Summary collapse
- VERSION =
'1.5.0'
Class Method Summary collapse
-
.callbacks ⇒ Object
:nodoc:.
-
.scram(&block) ⇒ Object
Stops all reactions while inside the (required) block.
-
.scrammed? ⇒ Boolean
:nodoc:.
Class Method Details
.callbacks ⇒ Object
:nodoc:
49 50 51 |
# File 'lib/active_record/reactor.rb', line 49 def callbacks # :nodoc: (self.public_instance_methods - ActiveRecord::Reactor.public_instance_methods).grep(/\A(before|around|after)_.+/) end |
.scram(&block) ⇒ Object
Stops all reactions while inside the (required) block.
58 59 60 61 62 63 64 65 66 67 |
# File 'lib/active_record/reactor.rb', line 58 def scram(&block) previously_scrammed = nil mutex.synchronize do previously_scrammed = @scrammed @scrammed = true end yield ensure mutex.synchronize { @scrammed = previously_scrammed } end |
.scrammed? ⇒ Boolean
:nodoc:
53 54 55 |
# File 'lib/active_record/reactor.rb', line 53 def scrammed? # :nodoc: !!@scrammed end |