Auditing mixin for model classes. Small problem


#1

I want to include common auditing functionality in my models. This
involves storing the changes made to a model in a seperate table :

I have created the functions in an Audit module :

module Audit
before_update :before_changes
after_update :after_changes

def before_changes
old=self.class.find(id).attributes
@changes=[]
attributes.each do |key, val|
if val != old[key]
change = Change.new(:primary_key_id=>id,
:table=>self.class.table_name,
:attribute=>self.class.human_attribute_name(key),
:old=>old[key],
:new=>val)
@changes << change
end
end
end

def after_changes
if(@changes.size>0)
@changes.each {|change| change.save}
end
end
end

I now want to include it like this in my model class :

class Customer < ActiveRecord::Base
include Audit

end

But i get the error : “undefined method ‘before_update’ for
Audit::Module”

I can change it like this so it works fine:

class Customer < ActiveRecord::Base
include Audit
before_update :before_changes
after_update :after_changes

end

But this is not an ideal solution. I’d rather only include the one
include.
Any ideas???

Thanks,
Chris


#2

I also want to include

“has_many :changes”

in each model that uses the mixin. I cannot include “has_many :changes”
in the module.


#3

On 2/22/06, Chris removed_email_address@domain.invalid wrote:

I also want to include

“has_many :changes”

in each model that uses the mixin. I cannot include “has_many :changes”
in the module.

I’d highly suggest looking into the various plugins around. But this
is probably what you’re looking for.

module Audit
def self.included(base)
base.before_save …
base.has_many :changes
end
end

http://ruby-doc.org/core/classes/Module.html#M000743


Rick O.
http://techno-weenie.net


#4

The acts_as_versioned plugin is pretty close I imagine.


#5

Thanks. YOu’re the man.

Have you seen a plugin anywhere that does this?


#6

On 2/23/06, Theodore M. removed_email_address@domain.invalid wrote:

The acts_as_versioned plugin is pretty close I imagine.

It looks like you’re using one table to audit all models. Acts as
Versioned uses a separate table for each model. The nice thing is
that each versioned record can also act like the actual method…


Rick O.
http://techno-weenie.net