Hooks (AKA Callbacks)
DataMapper supports callbacks using an aspect-oriented approach. You can define callbacks for any method as well as any class method arbitrarily.
Adding Instance-Level Advice
To declare advice (callback) for a specific method, first define a new method to be run when another is called, then define your point-cut.
1 class Post 2 include DataMapper::Resource 3 # ... key and properties here 4 before :save, :categorize 5 6 def categorize 7 # ... code here 8 end 9 end
Alternatively, you can declare the advice during the point-cut by supplying a block rather than a symbol representing a method.
1 class Post 2 include DataMapper::Resource 3 # ... key and properties here 4 5 before :save do 6 # ... code here 7 end 8 9 end
Adding Class-Level Advice
To install advice around a class method, use before_class_method or after_class_method:
1 class Post 2 include DataMapper::Resource 3 # ... key and properties here 4 before_class_method :find, :prepare 5 6 def self.prepare 7 # ... code here 8 end 9 end
Class level advice does not have access to any resulting instances from the class method, so they might not be the best fit for after_create or after_save.
Throw :halt, in the name of love…
In order to abort advice and prevent the advised method from being called, throw :halt
1 class Post 2 include DataMapper::Resource 3 # ... key and properties here 4 5 # This record will save properly 6 before :save do |post| 7 true 8 end 9 10 # But it will not be destroyed 11 before :destroy do |post| 12 throw :halt 13 end 14 end
Remember, if you throw :halt inside an after advice, the advised method will have already ran and returned. Because of this, the after advice will be the only thing halted.