Loading Observers Automatically From Their Own Folder

Observers are a great way of cleaning up and DRYing up your models. I use them quite a lot to deal with sending mails, logging messages and anything else that isn’t strictly the model’s responsibility.

One thing that’s bugged me since I discovered observers is that they are not invoked by default. Instead you have to explicitly state which observers should be loaded (usually in environment.rb)

If you plan on loading all of your observers from the environment when your app is booted (which is likely) then you can add the following to your environment.rb file to load them all automatically when you start your app:

# config/environment.rb
Dir.chdir("#{Rails.root}/app/models") do
  config.active_record.observers = Dir["*_observer.rb"].collect { |ob_name| ob_name.split(".").first }
end

This looks a little messy but all you are doing here is simply finding the names of all the observer files in the models folder and configuring your app to load each of them with

config.active_record.observers = ...

One other thing that bugs me about observers it that they are stored in the models folder by default. If you’re building a big app with several models and several observers this can get pretty cluttered and confusing.

To get around this I usually create a new folder in app/ called ‘observers’. I then move any observers I create into this folder.

To make sure this folder is loaded at startup I add the following to environment.rb

config.load_paths += %W{ #{Rails.root}/app/observers }

Simple!

If you decide to use this along with the previous tip on loading the observers automatically then you’ll have to change the name of the directory you’re looking in from models to observers:

# config/environment.rb
Dir.chdir("#{Rails.root}/app/observers") do
  config.active_record.observers = Dir["*_observer.rb"].collect {|ob_name| ob_name.split(".").first}
end

Remember to reboot your app after creating a new observer or making any changes to environment.rb.

Written by

Photo of Gavin Morrice
Gavin Morrice

Software engineer based in Scotland

Work with me

Need help with some code?

In my free time, I like to help people improve their code and skills on Codementor.
Contact me on Codementor