Skip to content

Instantly share code, notes, and snippets.

@unixmonkey
Created May 6, 2011 16:19
Show Gist options
  • Select an option

  • Save unixmonkey/959272 to your computer and use it in GitHub Desktop.

Select an option

Save unixmonkey/959272 to your computer and use it in GitHub Desktop.
Monkeypatch to get https://github.com/expectedbehavior/acts_as_archival to behave in Rails 3
module ExpectedBehavior
module ActsAsArchival
module ActMethods
def acts_as_archival
unless included_modules.include? InstanceMethods
include InstanceMethods
before_save :raise_if_not_archival
scope :archived, :conditions => ARCHIVED_CONDITIONS.call(self)
scope :unarchived, :conditions => UNARCHIVED_CONDITIONS
scope :archived_from_archive_number, lambda { |head_archive_number| {:conditions => [archived_at IS NOT NULL AND archive_number = ?', head_archive_number] } }
callbacks = ['archive','unarchive']
define_callbacks *[callbacks, {:terminator => 'result == false'}].flatten
callbacks.each do |callback|
eval <<-end_callbacks
def before_#{callback}(*args, &blk)
set_callback(:#{callback}, :before, *args, &blk)
end
def after_#{callback}(*args, &blk)
set_callback(:#{callback}, :after, *args, &blk)
end
end_callbacks
end
end
end
end
module InstanceMethods
def archive(head_archive_number=nil)
self.class.transaction do
begin
run_callbacks :archive, :before
unless self.archived?
head_archive_number ||= Digest::MD5.hexdigest("#{self.class.name}#{self.id}")
self.archived_at = DateTime.now
self.archive_number = head_archive_number
self.save!
self.archive_associations(head_archive_number)
end
run_callbacks :archive, :after
rescue
raise ActiveRecord::Rollback
end
end
self
end
def unarchive(head_archive_number=nil)
self.class.transaction do
begin
run_callbacks :unarchive, :before
if self.archived?
head_archive_number ||= self.archive_number
self.unarchive_associations(head_archive_number)
self.archived_at = nil
self.archive_number = nil
self.save!
end
run_callbacks :unarchive, :after
rescue
raise ActiveRecord::Rollback
end
end
self
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment