Skip to content

Commit

Permalink
added #changed_attributes to get access to the changes before a save …
Browse files Browse the repository at this point in the history
…[Chris Parker]
  • Loading branch information
bkeepers committed Mar 21, 2008
1 parent 646d898 commit 365f4b0
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 7 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG
@@ -1,6 +1,8 @@
acts_as_audited ChangeLog
-------------------------------------------------------------------------------

* 2008-03-21 - added #changed_attributes to get access to the changes before a save [Chris Parker]

0.5
* Added #revision_at for retrieving a revision from a specific time [Jacob Atzen]
* Fix error when getting revision from audit with no changes [Geoffrey Wiseman]
Expand Down
17 changes: 10 additions & 7 deletions lib/acts_as_audited.rb
Expand Up @@ -86,6 +86,11 @@ def acts_as_audited(options = {})
end

module InstanceMethods

def changed_attributes
@changed_attributes ||= {}
end

# Temporarily turns off auditing while saving.
def save_without_auditing
without_auditing { save }
Expand All @@ -99,8 +104,7 @@ def audited_attributes
# If called with no parameters, gets whether the current model has changed.
# If called with a single parameter, gets whether the parameter has changed.
def changed?(attr_name = nil)
@changed_attributes ||= {}
attr_name ? @changed_attributes.include?(attr_name.to_s) : !@changed_attributes.empty?
attr_name ? changed_attributes.include?(attr_name.to_s) : !changed_attributes.empty?
end

# Executes the block with the auditing callbacks disabled.
Expand Down Expand Up @@ -172,7 +176,7 @@ def audit_destroy
end

def write_audit(action = :update, user = nil)
self.audits.create :changes => @changed_attributes, :action => action.to_s, :user => user
self.audits.create :changes => changed_attributes, :action => action.to_s, :user => user
end

# clears current changed attributes. Called after save.
Expand All @@ -184,14 +188,13 @@ def clear_changed_attributes
def write_attribute_with_auditing(attr_name, attr_value)
attr_name = attr_name.to_s
if audited_attributes.include?(attr_name)
@changed_attributes ||= {}
# get original value
old_value = @changed_attributes[attr_name] ?
@changed_attributes[attr_name].first : self[attr_name]
old_value = changed_attributes[attr_name] ?
changed_attributes[attr_name].first : self[attr_name]
write_attribute_without_auditing(attr_name, attr_value)
new_value = self[attr_name]

@changed_attributes[attr_name] = [old_value, new_value] if new_value != old_value
changed_attributes[attr_name] = [old_value, new_value] if new_value != old_value
else
write_attribute_without_auditing(attr_name, attr_value)
end
Expand Down

0 comments on commit 365f4b0

Please sign in to comment.