require 'rubygems'
require 'data_mapper'
class Foo
include DataMapper::Resource
property :name, String, :key => true
before :create, do
puts 'Create: Only happens when saving a new object.'
end
before :update, do
puts 'Update: Only happens when saving an existing object.'
end
before :save, do
puts 'Save: Happens when either creating or updating an object.'
end
before :destroy, do
puts 'Destroy: Only happens when destroying an existing object.'
end
end
DataMapper.setup :default, 'sqlite::memory:'
DataMapper.finalize
DataMapper.auto_migrate!
puts "New Foo:"
f = Foo.new :name => "Fighter"
f.save
puts "\nUpdate Foo:"
f.name = "Bar"
f.save
puts "\nUpdate Foo again:"
f.update :name => "Baz"
puts "\nDestroy Foo:"
f.destroy
返回:
New Foo:
Save: Happens when either creating or updating an object.
Create: Only happens when saving a new object.
Update Foo:
Save: Happens when either creating or updating an object.
Update: Only happens when saving an existing object.
Update Foo again:
Save: Happens when either creating or updating an object.
Update: Only happens when saving an existing object.
Destroy Foo:
Destroy: Only happens when destroying an existing object.
因此,正如您所看到的,:save
每当在创建或更新之后发生某些事情时,:create
和/或:update
当您想要更好的控制级别时,您都希望使用钩子。