On Observer Registration

January 9, 2012 § Leave a comment

If you are using the observer pattern with your ActiveRecord models, you have to register the observers. I don’t see why this can’t be done automatically. I place all of my observers in app/observers so I can easily register all of them with a few line in my application.rb file.

# Register all the observers in the observers folder.
observers = []
pattern = File.join(Rails.application.config.root, 'app', 'observers', '**', '*.rb')
Dir.glob(pattern).each do |filename|
  observers << File.basename(filename, '.rb').to_sym
config.active_record.observers = observers

More on ActiveRecord Observers and an example application.rb.



Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

What’s this?

You are currently reading On Observer Registration at The On Blog.


%d bloggers like this: