Skip to content

Instantly share code, notes, and snippets.

@jeanbaptistebeck
Last active February 16, 2016 18:03
Show Gist options
  • Save jeanbaptistebeck/22ee743cb7edabb7ee3d to your computer and use it in GitHub Desktop.
Save jeanbaptistebeck/22ee743cb7edabb7ee3d to your computer and use it in GitHub Desktop.
Active Record Observer

Observers in Rails

gem 'rails-observers'

Life without observers

class Application < ActiveRecord::Base
  after_save :email_confirmation

  def open?
    status == 'Open'
  end

  def closed?
    status == 'Closed'
  end

  def pending?
    status == 'Pending'
  end

  def email_confirmation
    if status_changed?
      ApplicationMailer.closed_notification(self)  if closed?
      ApplicationMailer.open_notification(self)  if open?
      ApplicationMailer.pending_notification(self)  if pending?
    end
  end

end

ActiveRecord::Observers

class ApplicationObserver < ActiveRecord::Observer
  def after_save(appl)
    if status_changed?
      ApplicationMailer.closed_notification(appl)  if appl.closed?
      ApplicationMailer.open_notification(appl)  if appl.open?
      ApplicationMailer.pending_notification(appl)  if appl.pending?
    end
  end
end

Callbacks available

CALLBACKS = [
  :after_initialize, :after_find, :after_touch, :before_validation, :after_validation,
  :before_save, :around_save, :after_save, :before_create, :around_create,
  :after_create, :before_update, :around_update, :after_update,
  :before_destroy, :around_destroy, :after_destroy, :after_commit, :after_rollback
]

Adding your own callbacks

module Notifications
  def notify_completed
    notify_observers :after_complete
  end
end

class Action < ActiveRecord::Base
  include Notifications

  def complete!
    ...
    notify_completed
  end
end

class ActionObserver < ActiveRecord::Observer
  def after_complete(action)
    # your callback logic here
    ...
  end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment