Skip to content
ipoval edited this page Apr 6, 2011 · 9 revisions

Sequel::Observer wiki!

Observers

Observers are similar to callbacks, but with important differences. Whereas callbacks can pollute a model with code that isn’t directly related to its purpose, observers allow you to add the same functionality outside of a model. For example, it could be argued that a User model should not include code to send registration confirmation emails. Whenever you use callbacks with code that isn’t directly related to your model, you may want to consider creating an observer instead.

Creating Observers

For example, imagine a User model where we want to send an email every time a new user is created. Because sending emails is not directly related to our model’s purpose, we could create an observer to contain this functionality.

class UserObserver < Sequel::Observer
  def after_create(model_instance_record)
    # code to send confirmation email...
  end
end

The observer’s methods receive the instance of the model that caused the callback to fire as a parameter.

Registering Observers

Observers are conventionally placed inside of your app/models directory and can registered in your application’s config file.