ActiveRecord Observers

Share:

Listens: 0

Rails Coach

Technology


About a month ago, I talked about ActiveRecord Callbacks. Observers are a way of moving callbacks out of the Model. Usually this is done to adhere to the Single Responsibility principle. So, for example, programmers will move sending an email when a record is updated or created to an Observer. class UserObserver < ActiveRecord::Observer def after_create(user) UserMailer.sign_up(user).deliver end end   Observers should be included in your app/models folder and named using the same convention as your models. So in this case, this observer would be saved to /app/models/user_observer.rb. To load the observer in your application, you need to include this line in your config/application.rb config.active_record.observers = :user_observer   Finally, you can observe more than one model with the same observer. class SignUpObserver < ActiveRecord::Observer observer :user, :admin def after_create(user) UserMailer.sign_up(user).deliver end end   I personally like Observers when they help keep you from repeating code or increase code readability. In many cases, I simply keep callbacks in models and violate the Single Responsibility Principle.