I’ve the following model and I want to execute a method on save and update, problem is that the hook is not being executed on update.
class User
include DataMapper::Resource
include BCrypt
property :id, Serial
property :email, String, :index => true
property :crypted_password, String, :accessor => :private
...
attr_accessor :password, :password_confirmation
before :save, :encrypt_password!
# also tried the following with no success:
# before :update, :encrypt_password!
# and tried this but hell was never raised
# before :update do
# raise 'hell'
# end
def encrypt_password!
self.crypted_password = Password.create password
end
end
This spec fails:
it 'should call encrypt_password! on update' do
subject.save.should be_true
subject.should_receive(:encrypt_password!)
subject.update(:password => 'other-password', :password_confirmation => 'other-password').should be_true
end
And this passes:
it 'should call encrypt_password! on create' do
subject.should_receive(:encrypt_password!)
subject.save.should be_true
end
I’ve also tried with after :update in addition to after :save with no success.
Am I missing something?
I think this is a bug with datamapper but there are a couple of things that you could do to get around it until they fix the problem.
You could override the save method in your User class and then call then necessary encrypt_password! method from within your custom save method. Then simply call the parent’s save method to perform the datamapper db save.
Your save method could look like this
I know this violates the aspect-oriented design approach that datamapper has using hook but this will allow you to get your project done now if you need to.