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
end
config.active_record.observers = observers

More on ActiveRecord Observers and an example application.rb.

Advertisements

Where Am I?

You are currently browsing entries tagged with observers at The On Blog.

%d bloggers like this: