Extending AR to write audit columns


#1

Rails 2.2.2
Ruby 1.8.5

I am attempting to extend AR with a generalized audit attribute setter.
I have written this code, which does not work for reasons unknown to me.
Perhaps someone here can explain why it does not.

Put this in config/initializer as active_record_addins.rb

module ActiveRecord

module HLLAuditStamps

def self.included(base)
  super
  # alias_method_chain  :create,                :audit
  # is the same as:
  # alias_method        :create_without_audit,  :create
  # alias_method        :create,                :create_with_audit

  base.alias_method_chain  :create,                :audit
  base.alias_method_chain  :update,                :audit

end

private

def create_with_audit
  write_audit_fields
  # Now we call our alias to the original method
  create_without_audit
end

def normal_time_now
  if base.class.default_timezone == :utc
    return DateTime.now.utc
  else
    return DateTime.now
  end
end

def update_with_audit
  write_audit_fields
  update_without_audit
end

def write_audit_fields
  write_attribute('accessed_at', normal_time_now) if \
      respond_to?('accessed_at')
  write_attribute('accessed_on', normal_time_now) if \
      respond_to?('accessed_on')
end

end

end

What I intend is that whenever the AR create or update method is called
then the attributes specified in write_audit_fields are set to the value
provided by normal_time_now. They are not and I cannot tell why.

Any suggestions as to what I am doing wrong?


#2

James B. wrote:

Any suggestions as to what I am doing wrong?

Sorry this isn’t a direct answer to your question, but I just wanted to
ask if you have looked at any of the existing auditing plugins to see if
they support your needs?

For example:
http://github.com/collectiveidea/acts_as_audited/tree/master


#3

Robert W. wrote:

James B. wrote:

Any suggestions as to what I am doing wrong?

Sorry this isn’t a direct answer to your question, but I just wanted to
ask if you have looked at any of the existing auditing plugins to see if
they support your needs?

For example:
http://github.com/collectiveidea/acts_as_audited/tree/master

Despite the similarity of nomenclature, what I wish to do is different
than the service provided by that plugin, or acts_as_versioned, etc.
The example code given above is a minimalist representation of my
situation.

I have since read that the technique I am trying to employ has been
broken by a change to Rails (http://dev.rubyonrails.org/changeset/7749)
but I have been unable to discover a working alternative.