Created
July 30, 2010 22:05
-
-
Save drydevelopment/501399 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module LogModelUpdates | |
def self.included(base) | |
base.send :include, InstanceMethods | |
end | |
module InstanceMethods | |
attr_accessor :current_user | |
attr_accessor :row_updates | |
def before_save | |
log_row_updates | |
end | |
def after_save | |
create_row_updates! | |
end | |
def log_row_updates | |
@row_updates = [] | |
update_type = (self.new_record? ? "insert" : "update") | |
if update_type == "insert" | |
@row_updates << RowUpdate.new( :user_id => @current_user, | |
:row_id => (self.id || nil), | |
:update_type => update_type, | |
:table_name => self.class.table_name.to_s ) | |
else | |
self.changes.each do |attr| | |
@row_updates << RowUpdate.new( :user_id => @current_user.id, | |
:row_id => (self.id || nil), | |
:update_type => update_type, | |
:table_name => self.class.table_name.to_s, | |
:column_name => attr[0], | |
:before_value => attr[1][0], | |
:after_value => attr[1][1] ) | |
end | |
end | |
end | |
def create_row_updates! | |
@row_updates.each do |row| | |
row.row_id = self.id if row.row_id.nil? | |
begin | |
row.save! | |
rescue | |
# TODO: Handle failed insert | |
end | |
end | |
end | |
end | |
end |
The issue had to deal with the callbacks not being instantiated properly. The following code fixed it:
def self.extended(base)
base.before_save :log_row_updates
base.after_save :create_row_updates!
base.send :include, InstanceMethods
end
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It appears that when I attempt to insert each row update to the database in create_row_updates! the @row_updates instance variable doesn't retain it's value. It gives me a nil.each error. At the least, @row_updates should be equal to an empty array (line 19), right?