Low commit activity in last 3 years
A long-lived project that still receives updates
ActiveRecord Reactors provide a defined way to react on default or custom Active Record callbacks. Observers without the magic, and without the hassle.
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
 Dependencies

Runtime

 Project Readme

Gem Version Code Climate

Reactor - Controlled reactions on ActiveRecord callbacks

ActiveRecord Reactors provide a defined way to react on default or custom Active Record callbacks. You may think of them as Observers without the magic, and without the hassle.

Install

# In your Gemfile
gem 'activerecord-reactor'

Usage

Define a custom reactor class, where you would use an Observer:

class YummyReactor < ActiveRecord::Reactor
  after_create(record)
    puts "Yummy, #{record.color} #{record.class.name} created!" if record.is_a?(Fruit)
  end
end

Connect your models to the reactor:

class Fruit < ActiveRecord::Base
  attr_accessor :peel
  
  reactor :yummy

  def color; end
end

You can also use custom model callbacks:

class Tidy < ActiveRecord::Reactor
  def before_peel(record)
    record.wash!
  end

  def after_peel(record)
    GarbageCollector.dispose(record.peel)
  end
end

class Banana < Fruit
  # Use instead of define_model_callbacks if you want to register
  # the callback with reactors
  define_reactor_callbacks :peel

  # You can use the actual class if you do not want the reactor name end with 'Reactor'
  reactor Tidy

  def color
    'yellow'
  end

  def peel!
    run_callbacks :peel do
      self.peel = Object.new
    end
  end
end

Finally, you can temporarily shutdown any reactions on a reactor:

class Apple < Fruit; end

YummyReactor.scram do
  Apple.create! # hide this one from YummyReactor
end