This is a DataMapper plugin that provides observers for DataMapper resource classes. It’s compatible with DataMapper 0.9.1

Setup

DataMapper observer capabilities are automatically available when you ‘require dm-observers’ into your application.

Basic Usage

require 'dm-observers'

DataMapper.setup(:default, 'sqlite3::memory:')

class MyModel
  include DataMapper::Resource
  include DataMapper::Observers::Observable
  property :id, Integer, :key => true

  def my_instance_method
    puts "my_instance_method called"
  end
end

class MyObserver < DataMapper::Observers::Observer

  before :save do
    puts "before :save block..."
  end

  after :destroy do
    puts "after :destroy block..."
  end

  before :my_instance_method do
    puts "before :my_instance_method block..."
    # ...
  end

  before :my_instance_method do |object|
    puts "before :my_instance_method block with object parameter #{object.inspect}..."
    #...
  end

  # ...
end

MyObserver.instance.observed_class = MyModel

MyModel.auto_migrate!
object = MyModel.new

object.my_instance_method
---- output ----
before :my_instance_method block...
before :my_instance_method block with object parameter #<MyModel id=nil>...
my_instance_method called
---- output ----

object.save
---- output ----
before :save block...
---- output ----

object.destroy
---- output ----
after :destroy block...
---- output ----

The methods “before” and “after” take a target method parameter – the name of the method at the model to observe – and a block – the code to execute before/after the target method is executed. The syntax is pretty similar to model hooks, just that it doesn’t support class methods or method symbols yet.

The block supports a parameter, that will be filled with the object instance that sent the update notification to the observers.

Observers for DataMapper Resources

The observers defined for DataMapper Resources can be automatically added to the model, if the observer class name is prefixed with the name of the model to observe, and suffixed with ‘Observer’. Example:

class MyModel
  # ...
end

class MyModelObserver
  # ...
end

MyModelObserver.instance # The observer is automatically added to the MyModel class.

You can include all the observers instanciations at some bootstrap block of your project.

Custom messages to the observer

Additionally to the default hooks called on the observers, you can send a custom message to them using the notify_observers method:

class MyModel
  include DataMapper::Resource
  include DataMapper::Observers::Observable
  property :id, Integer, :key => true

  def do_something
    # ...
    MyModel.notify_observers(:purge_old_data, self)
  end
end

class MyModelObserver < DataMapper::Observers::Observer
  def purge_old_data(object)
    puts "Purge Old Data..."
    # ...
  end
end

MyModelObserver.instance
MyModel.new.do_something
---- output ----
Purge Old Data...
---- output ----