/memento

Undo for Rails/ActiveRecord - covers destroy, update and create

Primary LanguageRubyMIT LicenseMIT

memento

RubyGem/Plugin for undo in Rails/ActiveRecord - covers destroy, update and create actions.

Install

memento will only work with Rails 3.0 and Ruby 1.9.2.

as a ruby-gem

Add this line to your config/environment.rb:

config.gem "yolk-memento", :lib => 'memento', :source => 'http://gems.github.com'

and run

rake gems:install

as rails plugin

script/plugin install git://github.com/yolk/memento.git

Setup

memento needs two tables in your database, one to store “sessions” (sets of states) and the other to store “states” (aka snapshots of single models). To generate the necessary migration and migrate your database run:

script/generate memento_migration
rake db:migrate

memento assumes you have a user-model. Every session is owned by a user.

Configure your models

Then you have to tell every model you want to undo actions on that it should be watched by memento:

class Person < ActiveRecord::Base
  memento_changes
end

This will tell memento to create snapshots of the model when an new instance is created, an exisiting one is updated or destroyed.

If you want memento to only take snapshots on specific actions:

memento_changes :update, :destroy

This will take a snapshot only when an instance is updated or destroyed.

By default memento will ignore changes to the :updated_at and :created_at attributes. You can add further attributes to ignore with the :ignore option:

memento_changes :ignore => [:calculated_birthday, :friends_count]

This will ignore changes on the calculated_birthday and the firends_count-attributes. When memento saves a whole instance of your model before it is destroyed, those attributes will not be stored for later recovery. Only ignore attributes you can re-calculate from other data!

Action!

When you perform any of the configured actions on your model in isolation in your controller memento will not store any changes:

Person.create!(:name => "Blah")
Memento::Session.count # => 0

You have to wrap every action block you want memento to track in your controller with the memento-method:

memento do
  Person.create!(:name => "Blah")
end
Memento::Session.count # => 1

This assumes there is an method called “current_user” in your controllers. It will also set the HTTP-Header ‘X-Memento-Session-Id’ on your response.

If you want memento to watch changes outside of your controllers (for example inside the console) you can use:

Memento(user) do
  Person.create!(:name => "Blah")
end

Where the variable user is assumed to hold an instance of User.

Undo!

Undoing this changes is as simple as calling #undo on an memento-session-instance.

Memento::Session.first.undo

Copyright © 2009-2010 Yolk Sebastian Munz & Julia Soergel GbR. See LICENSE for details.