Everett is a substitute for Active Record Observer on Rails 5.
Put this in your Gemfile:
gem 'everett'
Run the installation generator with:
$ rails g everett:install
They will install the initializer into config/initializers/everett.rb
.
Observers allow you to implement trigger-like behavior outside the original classes.
You can put them anywhere, for example app/models/contact_observer.rb
:
class ContactObserver < Everett::Observer
def after_create(contact)
Rails.logger.info('New contact has been added!')
end
def after_destroy(contact)
Rails.logger.info("Contact with an id of #{contact.id} has been destroyed!")
end
end
This observer prints a log message when specific callbacks are triggered.
Just like Active Record Observer, the convention is to name observers after the class they observe.
If you need to change this, or want to use one observer for several classes, use observe
:
class NotificationsObserver < Everett::Observer
observe :comment, :like
def after_create(record)
# notifiy users of new comment or like
end
end
Note that you must register observers first to activate them.
This can be done by adding the following line into config/initializers/everett.rb
:
config.observers = :contact_observer, :notifications_observer
Since after_create_commit
, after_update_commit
and after_destroy_commit
were introduced in Rails 5,
you can also use them in observers:
class CommentObserver < Everett::Observer
def after_create_commit(comment)
CommentMailer.notification(comment).deliver_now
end
end
This observer sends an email after a record has been created.
Since Everett is highly compatible with Active Record Observer,
you can easily migrate from rails-observers.
All you need to do is as follows:
-class ContactObserver < ActiveRecord::Observer
+class ContactObserver < Everett::Observer
# config/application.rb
-config.active_record.observers = :contact_observer, :notifications_observer
# config/initializers/everett.rb
+Everett.configure do |config|
+ config.observers = :contact_observer, :notifications_observer
+end
If you find any bugs, please document them on the issues page.
You should follow the steps below.
- Fork the repository
- Create a feature branch:
git checkout -b add-new-feature
- Commit your changes:
git commit -am 'Add new feature'
- Push the branch:
git push origin add-new-feature
- Send us a pull request
The gem is available as open source under the terms of the MIT License.