How to hook into model attribute changes?

Hi,

What’s the best way to hook into any changes made to the value of a
single model attribute? I need to know when the encrypted_password
attribute on my User model changes i.e. when the user has changed their
password. I’m not interested in the actual changed value, I just need to
know when it’s been changed so that I can regenerate their API key as
well.

Thanks in advance.

John

Hi John

On Oct 22, 7:28 pm, John T. [email protected]
wrote:

Hi,

What’s the best way to hook into any changes made to the value of a
single model attribute? I need to know when the encrypted_password
attribute on my User model changes i.e. when the user has changed their
password. I’m not interested in the actual changed value, I just need to
know when it’s been changed so that I can regenerate their API key as
well.

cch: You should look into callbacks. For example, I use

def after_update(record)
log(record, “UPDATE”)
end

to record whether a change has been made

CCH wrote:

Hi John

On Oct 22, 7:28 pm, John T. [email protected]
wrote:

Hi,

What’s the best way to hook into any changes made to the value of a
single model attribute? I need to know when the encrypted_password
attribute on my User model changes i.e. when the user has changed their
password. I’m not interested in the actual changed value, I just need to
know when it’s been changed so that I can regenerate their API key as
well.

cch: You should look into callbacks. For example, I use

def after_update(record)
log(record, “UPDATE”)
end

to record whether a change has been made

Thanks. I did try that but the problem is that the user can change other
settings on the screen that lets them change their password and the API
key musn’t be regenerated if those other settings are changed. Hence, I
need to detect a changed password only.

You could try using this plugin and a callback (after_update maybe?)
to determine when to regenerate the API key:

http://svn.viney.net.nz/things/rails/plugins/acts_as_modified/README

On Oct 22, 8:46 am, John T. [email protected]

Thanks Andrew, I’ll try that out.

John T. wrote:

What’s the best way to hook into any changes made to the value of a
single model attribute? I need to know when the encrypted_password
attribute on my User model changes i.e. when the user has changed their
password. I’m not interested in the actual changed value, I just need to
know when it’s been changed so that I can regenerate their API key as
well.

Something like

class User
def encrypted_password=(ep)
self.api_key = API.gen_key(ep) # if ep != encrypted_password
super
end
end

The condition isn’t necessary in this case because the
encrypted_password is only set if a password change is
detected, not on every form submission by the user.


We develop, watch us RoR, in numbers too big to ignore.