Search code examples
ruby-on-railsredisactivemodel

How do I build an Observer for ToyStore model?


Given a model:

class User
  include Toy::Store
  attribute :name
end

Can I use ActiveModel::Observer to build an observer? I remove the ActiveRecord framework, as I am not using it in my Rails app.

Adding an observer like:

class UserObserver < ActiveModel::Observer
  def after_save(model)
    puts "Hello!"
  end
end

does not seem to work. Including the observer in the application configuration does not work, because the ActiveRecord framework is removed.


Solution

  • I also wanted to use Observers with Toy::Store too. It turns out that the normal object lifecycle events, like create, save, update, and delete that are observable in Rails are observable because of ActiveRecord. Toy Store objects are ActiveModel objects and don't have the same hooks. I did a deep dive on the subject in a blog post on Why Toy Store Doesn't Work With Observers.

    But, good news, it's still possible to use observers with toy store, it's just up to you to implement them. I also did a blog post on How to Use Observers With Toy::Store , but here's the gist of it: your Toy Object, in this case User, must include ActiveModel::Observing and must fire the event when it's appropriate for that model:

    class User
      include Toy::Store
      attribute :name
      after_save :notify_observers_save_occured
    
      private
    
      def notify_observers_save_occured
        self.class.notify_observers(:after_save, self)
      end
    
    end