Created
January 28, 2009 00:43
-
-
Save zmoazeni/53743 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
class AuditHelper | |
def self.rebuild_from_audit(audit) | |
changes_in_order = Audit.find(:all, :conditions => ['auditable_id = ? AND auditable_type = ? AND version <= ?', audit.auditable_id, audit.auditable_type, audit.version], :order => "version") | |
current_attributes = {} | |
changes_in_order.each do |audit| | |
current_attributes.merge!(audit.changes || {}) | |
current_attributes.merge!(:version => audit.version) | |
end | |
obj = audit.auditable_type.constantize.new(current_attributes) | |
end | |
def self.revision_at(model, date_or_time) | |
max_audit = model.audits.find(:first, :conditions => ["created_at <= ?", date_or_time], :order => "created_at DESC") | |
return nil unless max_audit | |
changes_in_order = model.audits.find(:all, :conditions => ['version <= ?', max_audit.version], :order => "version") | |
current_attributes = {} | |
changes_in_order.each do |audit| | |
current_attributes.merge!(audit.changes || {}) | |
current_attributes.merge!(:version => audit.version) | |
end | |
obj = model.dup | |
# obj.send :instance_variable_set, '@attributes', model.attributes_before_type_cast | |
obj.attributes = current_attributes | |
# Remove any association proxies so that they will be recreated | |
# and reference the correct object for this revision. The only way | |
# to determine if an instance variable is a proxy object is to | |
# see if it responds to certain methods, as it forwards almost | |
# everything to its target. | |
for ivar in obj.instance_variables | |
proxy = obj.instance_variable_get ivar | |
if !proxy.nil? and proxy.respond_to? :proxy_respond_to? | |
obj.instance_variable_set ivar, nil | |
end | |
end | |
obj | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment