bkwld-paper_trail 2.3.2

Sign up to get free protection for your applications and to get access to all the features.
Files changed (78) hide show
  1. data/.gitignore +10 -0
  2. data/.travis.yml +5 -0
  3. data/Gemfile +2 -0
  4. data/MIT-LICENSE +20 -0
  5. data/README.md +663 -0
  6. data/Rakefile +15 -0
  7. data/lib/generators/paper_trail/USAGE +2 -0
  8. data/lib/generators/paper_trail/install_generator.rb +20 -0
  9. data/lib/generators/paper_trail/templates/add_object_changes_column_to_versions.rb +9 -0
  10. data/lib/generators/paper_trail/templates/create_versions.rb +19 -0
  11. data/lib/paper_trail.rb +87 -0
  12. data/lib/paper_trail/config.rb +11 -0
  13. data/lib/paper_trail/controller.rb +76 -0
  14. data/lib/paper_trail/has_paper_trail.rb +228 -0
  15. data/lib/paper_trail/version.rb +159 -0
  16. data/lib/paper_trail/version_number.rb +3 -0
  17. data/paper_trail.gemspec +24 -0
  18. data/test/dummy/Rakefile +7 -0
  19. data/test/dummy/app/controllers/application_controller.rb +17 -0
  20. data/test/dummy/app/controllers/test_controller.rb +5 -0
  21. data/test/dummy/app/controllers/widgets_controller.rb +23 -0
  22. data/test/dummy/app/helpers/application_helper.rb +2 -0
  23. data/test/dummy/app/models/animal.rb +4 -0
  24. data/test/dummy/app/models/article.rb +12 -0
  25. data/test/dummy/app/models/authorship.rb +5 -0
  26. data/test/dummy/app/models/book.rb +5 -0
  27. data/test/dummy/app/models/cat.rb +2 -0
  28. data/test/dummy/app/models/document.rb +4 -0
  29. data/test/dummy/app/models/dog.rb +2 -0
  30. data/test/dummy/app/models/elephant.rb +3 -0
  31. data/test/dummy/app/models/fluxor.rb +3 -0
  32. data/test/dummy/app/models/foo_widget.rb +2 -0
  33. data/test/dummy/app/models/person.rb +5 -0
  34. data/test/dummy/app/models/post.rb +4 -0
  35. data/test/dummy/app/models/song.rb +12 -0
  36. data/test/dummy/app/models/widget.rb +5 -0
  37. data/test/dummy/app/models/wotsit.rb +4 -0
  38. data/test/dummy/app/versions/post_version.rb +3 -0
  39. data/test/dummy/app/views/layouts/application.html.erb +14 -0
  40. data/test/dummy/config.ru +4 -0
  41. data/test/dummy/config/application.rb +45 -0
  42. data/test/dummy/config/boot.rb +10 -0
  43. data/test/dummy/config/database.yml +22 -0
  44. data/test/dummy/config/environment.rb +5 -0
  45. data/test/dummy/config/environments/development.rb +26 -0
  46. data/test/dummy/config/environments/production.rb +49 -0
  47. data/test/dummy/config/environments/test.rb +35 -0
  48. data/test/dummy/config/initializers/backtrace_silencers.rb +7 -0
  49. data/test/dummy/config/initializers/inflections.rb +10 -0
  50. data/test/dummy/config/initializers/mime_types.rb +5 -0
  51. data/test/dummy/config/initializers/secret_token.rb +7 -0
  52. data/test/dummy/config/initializers/session_store.rb +8 -0
  53. data/test/dummy/config/locales/en.yml +5 -0
  54. data/test/dummy/config/routes.rb +3 -0
  55. data/test/dummy/db/migrate/20110208155312_set_up_test_tables.rb +120 -0
  56. data/test/dummy/db/schema.rb +103 -0
  57. data/test/dummy/db/test.sqlite3 +0 -0
  58. data/test/dummy/public/404.html +26 -0
  59. data/test/dummy/public/422.html +26 -0
  60. data/test/dummy/public/500.html +26 -0
  61. data/test/dummy/public/favicon.ico +0 -0
  62. data/test/dummy/public/javascripts/application.js +2 -0
  63. data/test/dummy/public/javascripts/controls.js +965 -0
  64. data/test/dummy/public/javascripts/dragdrop.js +974 -0
  65. data/test/dummy/public/javascripts/effects.js +1123 -0
  66. data/test/dummy/public/javascripts/prototype.js +6001 -0
  67. data/test/dummy/public/javascripts/rails.js +175 -0
  68. data/test/dummy/public/stylesheets/.gitkeep +0 -0
  69. data/test/dummy/script/rails +6 -0
  70. data/test/functional/controller_test.rb +71 -0
  71. data/test/functional/thread_safety_test.rb +26 -0
  72. data/test/integration/navigation_test.rb +7 -0
  73. data/test/paper_trail_test.rb +27 -0
  74. data/test/support/integration_case.rb +5 -0
  75. data/test/test_helper.rb +49 -0
  76. data/test/unit/inheritance_column_test.rb +43 -0
  77. data/test/unit/model_test.rb +925 -0
  78. metadata +236 -0
data/.gitignore ADDED
@@ -0,0 +1,10 @@
1
+ test/debug.log
2
+ test/paper_trail_plugin.sqlite3.db
3
+ test/dummy/log/*
4
+ test/dummy/tmp/*
5
+ coverage
6
+ pkg/*
7
+ *.gem
8
+ .bundle
9
+ Gemfile.lock
10
+ vendor/*
data/.travis.yml ADDED
@@ -0,0 +1,5 @@
1
+ rvm:
2
+ - 1.8.7
3
+ - 1.9.2
4
+ - ree
5
+
data/Gemfile ADDED
@@ -0,0 +1,2 @@
1
+ source :rubygems
2
+ gemspec
data/MIT-LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ Copyright (c) 2009 Andy Stewart, AirBlade Software Ltd.
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,663 @@
1
+ # PaperTrail [![Build Status](http://travis-ci.org/airblade/paper_trail.png)](http://travis-ci.org/airblade/paper_trail)
2
+
3
+ PaperTrail lets you track changes to your models' data. It's good for auditing or versioning. You can see how a model looked at any stage in its lifecycle, revert it to any version, and even undelete it after it's been destroyed.
4
+
5
+ There's an excellent [Railscast on implementing Undo with Paper Trail](http://railscasts.com/episodes/255-undo-with-paper-trail).
6
+
7
+
8
+ ## Features
9
+
10
+ * Stores every create, update and destroy (or only the lifecycle events you specify).
11
+ * Does not store updates which don't change anything.
12
+ * Allows you to specify attributes (by inclusion or exclusion) which must change for a Version to be stored.
13
+ * Allows you to get at every version, including the original, even once destroyed.
14
+ * Allows you to get at every version even if the schema has since changed.
15
+ * Allows you to get at the version as of a particular time.
16
+ * Option to automatically restore `has_one` associations as they were at the time.
17
+ * Automatically records who was responsible via your controller. PaperTrail calls `current_user` by default, if it exists, but you can have it call any method you like.
18
+ * Allows you to set who is responsible at model-level (useful for migrations).
19
+ * Allows you to store arbitrary model-level metadata with each version (useful for filtering versions).
20
+ * Allows you to store arbitrary controller-level information with each version, e.g. remote IP.
21
+ * Can be turned off/on per class (useful for migrations).
22
+ * Can be turned off/on per request (useful for testing with an external service).
23
+ * Can be turned off/on globally (useful for testing).
24
+ * No configuration necessary.
25
+ * Stores everything in a single database table by default (generates migration for you), or can use separate tables for separate models.
26
+ * Supports custom version classes so different models' versions can have different behaviour.
27
+ * Supports custom name for versions association.
28
+ * Thoroughly tested.
29
+ * Threadsafe.
30
+
31
+
32
+ ## Rails Version
33
+
34
+ Works on Rails 3 and Rails 2.3. The Rails 3 code is on the `master` branch and tagged `v2.x`. The Rails 2.3 code is on the `rails2` branch and tagged `v1.x`. Please note I'm not adding new features to the Rails 2.3 codebase.
35
+
36
+
37
+ ## API Summary
38
+
39
+ When you declare `has_paper_trail` in your model, you get these methods:
40
+
41
+ class Widget < ActiveRecord::Base
42
+ has_paper_trail # you can pass various options here
43
+ end
44
+
45
+ # Returns this widget's versions.
46
+ widget.versions
47
+
48
+ # Return the version this widget was reified from, or nil if it is live.
49
+ widget.version
50
+
51
+ # Returns true if this widget is the current, live one; or false if it is from a previous version.
52
+ widget.live?
53
+
54
+ # Returns who put the widget into its current state.
55
+ widget.originator
56
+
57
+ # Returns the widget (not a version) as it looked at the given timestamp.
58
+ widget.version_at(timestamp)
59
+
60
+ # Returns the widget (not a version) as it was most recently.
61
+ widget.previous_version
62
+
63
+ # Returns the widget (not a version) as it became next.
64
+ widget.next_version
65
+
66
+ # Turn PaperTrail off for all widgets.
67
+ Widget.paper_trail_off
68
+
69
+ # Turn PaperTrail on for all widgets.
70
+ Widget.paper_trail_on
71
+
72
+ And a `Version` instance has these methods:
73
+
74
+ # Returns the item restored from this version.
75
+ version.reify(options = {})
76
+
77
+ # Returns who put the item into the state stored in this version.
78
+ version.originator
79
+
80
+ # Returns who changed the item from the state it had in this version.
81
+ version.terminator
82
+ version.whodunnit
83
+
84
+ # Returns the next version.
85
+ version.next
86
+
87
+ # Returns the previous version.
88
+ version.previous
89
+
90
+ # Returns the index of this version in all the versions.
91
+ version.index
92
+
93
+ # Returns the event that caused this version (create|update|destroy).
94
+ version.event
95
+
96
+ In your controllers you can override these methods:
97
+
98
+ # Returns the user who is responsible for any changes that occur.
99
+ # Defaults to current_user.
100
+ user_for_paper_trail
101
+
102
+ # Returns any information about the controller or request that you want
103
+ # PaperTrail to store alongside any changes that occur.
104
+ info_for_paper_trail
105
+
106
+
107
+ ## Basic Usage
108
+
109
+ PaperTrail is simple to use. Just add 15 characters to a model to get a paper trail of every `create`, `update`, and `destroy`.
110
+
111
+ class Widget < ActiveRecord::Base
112
+ has_paper_trail
113
+ end
114
+
115
+ This gives you a `versions` method which returns the paper trail of changes to your model.
116
+
117
+ >> widget = Widget.find 42
118
+ >> widget.versions # [<Version>, <Version>, ...]
119
+
120
+ Once you have a version, you can find out what happened:
121
+
122
+ >> v = widget.versions.last
123
+ >> v.event # 'update' (or 'create' or 'destroy')
124
+ >> v.whodunnit # '153' (if the update was via a controller and
125
+ # the controller has a current_user method,
126
+ # here returning the id of the current user)
127
+ >> v.created_at # when the update occurred
128
+ >> widget = v.reify # the widget as it was before the update;
129
+ # would be nil for a create event
130
+
131
+ PaperTrail stores the pre-change version of the model, unlike some other auditing/versioning plugins, so you can retrieve the original version. This is useful when you start keeping a paper trail for models that already have records in the database.
132
+
133
+ >> widget = Widget.find 153
134
+ >> widget.name # 'Doobly'
135
+
136
+ # Add has_paper_trail to Widget model.
137
+
138
+ >> widget.versions # []
139
+ >> widget.update_attributes :name => 'Wotsit'
140
+ >> widget.versions.first.reify.name # 'Doobly'
141
+ >> widget.versions.first.event # 'update'
142
+
143
+ This also means that PaperTrail does not waste space storing a version of the object as it currently stands. The `versions` method gives you previous versions; to get the current one just call a finder on your `Widget` model as usual.
144
+
145
+ Here's a helpful table showing what PaperTrail stores:
146
+
147
+ <table>
148
+ <tr>
149
+ <th>Event</th>
150
+ <th>Model Before</th>
151
+ <th>Model After</th>
152
+ </tr>
153
+ <tr>
154
+ <td>create</td>
155
+ <td>nil</td>
156
+ <td>widget</td>
157
+ </tr>
158
+ <tr>
159
+ <td>update</td>
160
+ <td>widget</td>
161
+ <td>widget'</td>
162
+ <tr>
163
+ <td>destroy</td>
164
+ <td>widget</td>
165
+ <td>nil</td>
166
+ </tr>
167
+ </table>
168
+
169
+ PaperTrail stores the values in the Model Before column. Most other auditing/versioning plugins store the After column.
170
+
171
+
172
+ ## Choosing Lifecycle Events To Monitor
173
+
174
+ You can choose which events to track with the `on` option. For example, to ignore `create` events:
175
+
176
+ class Article < ActiveRecord::Base
177
+ has_paper_trail :on => [:update, :destroy]
178
+ end
179
+
180
+
181
+
182
+ ## Choosing Attributes To Monitor
183
+
184
+ You can ignore changes to certain attributes like this:
185
+
186
+ class Article < ActiveRecord::Base
187
+ has_paper_trail :ignore => [:title, :rating]
188
+ end
189
+
190
+ This means that changes to just the `title` or `rating` will not store another version of the article. It does not mean that the `title` and `rating` attributes will be ignored if some other change causes a new `Version` to be created. For example:
191
+
192
+ >> a = Article.create
193
+ >> a.versions.length # 1
194
+ >> a.update_attributes :title => 'My Title', :rating => 3
195
+ >> a.versions.length # 1
196
+ >> a.update_attributes :content => 'Hello'
197
+ >> a.versions.length # 2
198
+ >> a.versions.last.reify.title # 'My Title'
199
+
200
+ Or, you can specify a list of all attributes you care about:
201
+
202
+ class Article < ActiveRecord::Base
203
+ has_paper_trail :only => [:title]
204
+ end
205
+
206
+ This means that only changes to the `title` will save a version of the article:
207
+
208
+ >> a = Article.create
209
+ >> a.versions.length # 1
210
+ >> a.update_attributes :title => 'My Title'
211
+ >> a.versions.length # 2
212
+ >> a.update_attributes :content => 'Hello'
213
+ >> a.versions.length # 2
214
+
215
+ Passing both `:ignore` and `:only` options will result in the article being saved if a changed attribute is included in `:only` but not in `:ignore`.
216
+
217
+
218
+ ## Reverting And Undeleting A Model
219
+
220
+ PaperTrail makes reverting to a previous version easy:
221
+
222
+ >> widget = Widget.find 42
223
+ >> widget.update_attributes :name => 'Blah blah'
224
+ # Time passes....
225
+ >> widget = widget.versions.last.reify # the widget as it was before the update
226
+ >> widget.save # reverted
227
+
228
+ Alternatively you can find the version at a given time:
229
+
230
+ >> widget = widget.version_at(1.day.ago) # the widget as it was one day ago
231
+ >> widget.save # reverted
232
+
233
+ Note `version_at` gives you the object, not a version, so you don't need to call `reify`.
234
+
235
+ Undeleting is just as simple:
236
+
237
+ >> widget = Widget.find 42
238
+ >> widget.destroy
239
+ # Time passes....
240
+ >> widget = Version.find(153).reify # the widget as it was before it was destroyed
241
+ >> widget.save # the widget lives!
242
+
243
+ In fact you could use PaperTrail to implement an undo system, though I haven't had the opportunity yet to do it myself. However [Ryan Bates has](http://railscasts.com/episodes/255-undo-with-paper-trail)!
244
+
245
+
246
+ ## Navigating Versions
247
+
248
+ You can call `previous_version` and `next_version` on an item to get it as it was/became. Note that these methods reify the item for you.
249
+
250
+ >> widget = Widget.find 42
251
+ >> widget.versions.length # 4 for example
252
+ >> widget = widget.previous_version # => widget == widget.versions.last.reify
253
+ >> widget = widget.previous_version # => widget == widget.versions[-2].reify
254
+ >> widget.next_version # => widget == widget.versions.last.reify
255
+ >> widget.next_version # nil
256
+
257
+ As an aside, I'm undecided about whether `widget.versions.last.next_version` should return `nil` or `self` (i.e. `widget`). Let me know if you have a view.
258
+
259
+ If instead you have a particular `version` of an item you can navigate to the previous and next versions.
260
+
261
+ >> widget = Widget.find 42
262
+ >> version = widget.versions[-2] # assuming widget has several versions
263
+ >> previous = version.previous
264
+ >> next = version.next
265
+
266
+ You can find out which of an item's versions yours is:
267
+
268
+ >> current_version_number = version.index # 0-based
269
+
270
+ Finally, if you got an item by reifying one of its versions, you can navigate back to the version it came from:
271
+
272
+ >> latest_version = Widget.find(42).versions.last
273
+ >> widget = latest_version.reify
274
+ >> widget.version == latest_version # true
275
+
276
+ You can find out whether a model instance is the current, live one -- or whether it came instead from a previous version -- with `live?`:
277
+
278
+ >> widget = Widget.find 42
279
+ >> widget.live? # true
280
+ >> widget = widget.versions.last.reify
281
+ >> widget.live? # false
282
+
283
+
284
+ ## Finding Out Who Was Responsible For A Change
285
+
286
+ If your `ApplicationController` has a `current_user` method, PaperTrail will store the value it returns in the `version`'s `whodunnit` column. Note that this column is a string so you will have to convert it to an integer if it's an id and you want to look up the user later on:
287
+
288
+ >> last_change = Widget.versions.last
289
+ >> user_who_made_the_change = User.find last_change.whodunnit.to_i
290
+
291
+ You may want PaperTrail to call a different method to find out who is responsible. To do so, override the `user_for_paper_trail` method in your controller like this:
292
+
293
+ class ApplicationController
294
+ def user_for_paper_trail
295
+ logged_in? ? current_member : 'Public user' # or whatever
296
+ end
297
+ end
298
+
299
+ In a migration or in `script/console` you can set who is responsible like this:
300
+
301
+ >> PaperTrail.whodunnit = 'Andy Stewart'
302
+ >> widget.update_attributes :name => 'Wibble'
303
+ >> widget.versions.last.whodunnit # Andy Stewart
304
+
305
+ N.B. A `version`'s `whodunnit` records who changed the object causing the `version` to be stored. Because a `version` stores the object as it looked before the change (see the table above), `whodunnit` returns who stopped the object looking like this -- not who made it look like this. Hence `whodunnit` is aliased as `terminator`.
306
+
307
+ To find out who made a `version`'s object look that way, use `version.originator`. And to find out who made a "live" object look like it does, use `originator` on the object.
308
+
309
+ >> widget = Widget.find 153 # assume widget has 0 versions
310
+ >> PaperTrail.whodunnit = 'Alice'
311
+ >> widget.update_attributes :name => 'Yankee'
312
+ >> widget.originator # 'Alice'
313
+ >> PaperTrail.whodunnit = 'Bob'
314
+ >> widget.update_attributes :name => 'Zulu'
315
+ >> widget.originator # 'Bob'
316
+ >> first_version, last_version = widget.versions.first, widget.versions.last
317
+ >> first_version.whodunnit # 'Alice'
318
+ >> first_version.originator # nil
319
+ >> first_version.terminator # 'Alice'
320
+ >> last_version.whodunnit # 'Bob'
321
+ >> last_version.originator # 'Alice'
322
+ >> last_version.terminator # 'Bob'
323
+
324
+
325
+ ## Custom Version Classes
326
+
327
+ You can specify custom version subclasses with the `:class_name` option:
328
+
329
+ class Post < ActiveRecord::Base
330
+ has_paper_trail :class_name => 'PostVersion'
331
+ end
332
+
333
+ class PostVersion < Version
334
+ # custom behaviour, e.g:
335
+ set_table_name :post_versions
336
+ end
337
+
338
+ This allows you to store each model's versions in a separate table, which is useful if you have a lot of versions being created.
339
+
340
+ Alternatively you could store certain metadata for one type of version, and other metadata for other versions.
341
+
342
+ You can also specify a custom name for the versions association. This is useful if you already have a `versions` method on your model. For example:
343
+
344
+ class Post < ActiveRecord::Base
345
+ has_paper_trail :versions => :paper_trail_versions
346
+
347
+ # Existing versions method. We don't want to clash.
348
+ def versions
349
+ ...
350
+ end
351
+ end
352
+
353
+
354
+ ## Associations
355
+
356
+ I haven't yet found a good way to get PaperTrail to automatically restore associations when you reify a model. See [here for a little more info](http://airbladesoftware.com/notes/undo-and-redo-with-papertrail).
357
+
358
+ If you can think of a good way to achieve this, please let me know.
359
+
360
+
361
+ ## Has-One Associations
362
+
363
+ PaperTrail can restore `:has_one` associations as they were at (actually, 3 seconds before) the time.
364
+
365
+ class Treasure < ActiveRecord::Base
366
+ has_one :location
367
+ end
368
+
369
+ >> treasure.amount # 100
370
+ >> treasure.location.latitude # 12.345
371
+
372
+ >> treasure.update_attributes :amount => 153
373
+ >> treasure.location.update_attributes :latitude => 54.321
374
+
375
+ >> t = treasure.versions.last.reify(:has_one => true)
376
+ >> t.amount # 100
377
+ >> t.location.latitude # 12.345
378
+
379
+ The implementation is complicated by the edge case where the parent and child are updated in one go, e.g. in one web request or database transaction. PaperTrail doesn't know about different models being updated "together", so you can't ask it definitively to get the child as it was before the joint parent-and-child update.
380
+
381
+ The correct solution is to make PaperTrail aware of requests or transactions (c.f. [Efficiency's transaction ID middleware](http://github.com/efficiency20/ops_middleware/blob/master/lib/e20/ops/middleware/transaction_id_middleware.rb)). In the meantime we work around the problem by finding the child as it was a few seconds before the parent was updated. By default we go 3 seconds before but you can change this by passing the desired number of seconds to the `:has_one` option:
382
+
383
+ >> t = treasure.versions.last.reify(:has_one => 1) # look back 1 second instead of 3
384
+
385
+ If you are shuddering, take solace from knowing PaperTrail opts out of these shenanigans by default. This means your `:has_one` associated objects will be the live ones, not the ones the user saw at the time. Since PaperTrail doesn't auto-restore `:has_many` associations (I can't get it to work) or `:belongs_to` (I ran out of time looking at `:has_many`), this at least makes your associations wrong consistently ;)
386
+
387
+
388
+
389
+ ## Has-Many-Through Associations
390
+
391
+ PaperTrail can track most changes to the join table. Specifically it can track all additions but it can only track removals which fire the `after_destroy` callback on the join table. Here are some examples:
392
+
393
+ Given these models:
394
+
395
+ class Book < ActiveRecord::Base
396
+ has_many :authorships, :dependent => :destroy
397
+ has_many :authors, :through => :authorships, :source => :person
398
+ has_paper_trail
399
+ end
400
+
401
+ class Authorship < ActiveRecord::Base
402
+ belongs_to :book
403
+ belongs_to :person
404
+ has_paper_trail # NOTE
405
+ end
406
+
407
+ class Person < ActiveRecord::Base
408
+ has_many :authorships, :dependent => :destroy
409
+ has_many :books, :through => :authorships
410
+ has_paper_trail
411
+ end
412
+
413
+ Then each of the following will store authorship versions:
414
+
415
+ >> @book.authors << @dostoyevsky
416
+ >> @book.authors.create :name => 'Tolstoy'
417
+ >> @book.authorships.last.destroy
418
+ >> @book.authorships.clear
419
+
420
+ But none of these will:
421
+
422
+ >> @book.authors.delete @tolstoy
423
+ >> @book.author_ids = [@solzhenistyn.id, @dostoyevsky.id]
424
+ >> @book.authors = []
425
+
426
+ Having said that, you can apparently get all these working (I haven't tested it myself) with this [monkey patch](http://stackoverflow.com/questions/2381033/how-to-create-a-full-audit-log-in-rails-for-every-table/2381411#2381411):
427
+
428
+ # In config/initializers/core_extensions.rb or lib/core_extensions.rb
429
+ ActiveRecord::Associations::HasManyThroughAssociation.class_eval do
430
+ def delete_records(records)
431
+ klass = @reflection.through_reflection.klass
432
+ records.each do |associate|
433
+ klass.destroy_all(construct_join_attributes(associate))
434
+ end
435
+ end
436
+ end
437
+
438
+ The difference is the call to `destroy_all` instead of `delete_all` in [the original](http://github.com/rails/rails/blob/master/activerecord/lib/active_record/associations/has_many_through_association.rb#L76-81).
439
+
440
+
441
+ There may be a way to store authorship versions, probably using association callbacks, no matter how the collection is manipulated but I haven't found it yet. Let me know if you do.
442
+
443
+
444
+ ## Storing metadata
445
+
446
+ You can store arbitrary model-level metadata alongside each version like this:
447
+
448
+ class Article < ActiveRecord::Base
449
+ belongs_to :author
450
+ has_paper_trail :meta => { :author_id => Proc.new { |article| article.author_id },
451
+ :word_count => :count_words,
452
+ :answer => 42 }
453
+ def count_words
454
+ 153
455
+ end
456
+ end
457
+
458
+ PaperTrail will call your proc with the current article and store the result in the `author_id` column of the `versions` table. (Remember to add your metadata columns to the table.)
459
+
460
+ Why would you do this? In this example, `author_id` is an attribute of `Article` and PaperTrail will store it anyway in serialized (YAML) form in the `object` column of the `version` record. But let's say you wanted to pull out all versions for a particular author; without the metadata you would have to deserialize (reify) each `version` object to see if belonged to the author in question. Clearly this is inefficient. Using the metadata you can find just those versions you want:
461
+
462
+ Version.all(:conditions => ['author_id = ?', author_id])
463
+
464
+ Note you can pass a symbol as a value in the `meta` hash to signal a method to call.
465
+
466
+ You can also store any information you like from your controller. Just override the `info_for_paper_trail` method in your controller to return a hash whose keys correspond to columns in your `versions` table. E.g.:
467
+
468
+ class ApplicationController
469
+ def info_for_paper_trail
470
+ { :ip => request.remote_ip, :user_agent => request.user_agent }
471
+ end
472
+ end
473
+
474
+ Remember to add those extra columns to your `versions` table ;)
475
+
476
+
477
+ ## Diffing Versions
478
+
479
+ There are two scenarios: diffing adjacent versions and diffing non-adjacent versions.
480
+
481
+ The best way to diff adjacent versions is to get PaperTrail to do it for you. If you add an `object_changes` text column to your `versions` table, either at installation time with the `--with-changes` option or manually, PaperTrail will store the `changes` diff (excluding any attributes PaperTrail is ignoring) in each `update` version. You can use the `version.changeset` method to retrieve it. For example:
482
+
483
+ >> widget = Widget.create :name => 'Bob'
484
+ >> widget.versions.last.changeset # {}
485
+ >> widget.update_attributes :name => 'Robert'
486
+ >> widget.versions.last.changeset # {'name' => ['Bob', 'Robert']}
487
+
488
+ Note PaperTrail only stores the changes for updates; there's no point storing them for created or destroyed objects.
489
+
490
+ Please be aware that PaperTrail doesn't use diffs internally. When I designed PaperTrail I wanted simplicity and robustness so I decided to make each version of an object self-contained. A version stores all of its object's data, not a diff from the previous version. This means you can delete any version without affecting any other.
491
+
492
+ To diff non-adjacent versions you'll have to write your own code. These libraries may help:
493
+
494
+ For diffing two strings:
495
+
496
+ * [htmldiff](http://github.com/myobie/htmldiff): expects but doesn't require HTML input and produces HTML output. Works very well but slows down significantly on large (e.g. 5,000 word) inputs.
497
+ * [differ](http://github.com/pvande/differ): expects plain text input and produces plain text/coloured/HTML/any output. Can do character-wise, word-wise, line-wise, or arbitrary-boundary-string-wise diffs. Works very well on non-HTML input.
498
+ * [diff-lcs](http://github.com/halostatue/ruwiki/tree/master/diff-lcs/trunk): old-school, line-wise diffs.
499
+
500
+ For diffing two ActiveRecord objects:
501
+
502
+ * [Jeremy Weiskotten's PaperTrail fork](http://github.com/jeremyw/paper_trail/blob/master/lib/paper_trail/has_paper_trail.rb#L151-156): uses ActiveSupport's diff to return an array of hashes of the changes.
503
+ * [activerecord-diff](http://github.com/tim/activerecord-diff): rather like ActiveRecord::Dirty but also allows you to specify which columns to compare.
504
+
505
+
506
+ ## Turning PaperTrail Off/On
507
+
508
+ Sometimes you don't want to store changes. Perhaps you are only interested in changes made by your users and don't need to store changes you make yourself in, say, a migration -- or when testing your application.
509
+
510
+ You can turn PaperTrail on or off in three ways: globally, per request, or per class.
511
+
512
+ ### Globally
513
+
514
+ On a global level you can turn PaperTrail off like this:
515
+
516
+ >> PaperTrail.enabled = false
517
+
518
+ For example, you might want to disable PaperTrail in your Rails application's test environment to speed up your tests. This will do it:
519
+
520
+ # in config/environments/test.rb
521
+ config.after_initialize do
522
+ PaperTrail.enabled = false
523
+ end
524
+
525
+ If you disable PaperTrail in your test environment but want to enable it for specific tests, you can add a helper like this to your test helper:
526
+
527
+ # in test/test_helper.rb
528
+ def with_versioning
529
+ was_enabled = PaperTrail.enabled?
530
+ PaperTrail.enabled = true
531
+ begin
532
+ yield
533
+ ensure
534
+ PaperTrail.enabled = was_enabled
535
+ end
536
+ end
537
+
538
+ And then use it in your tests like this:
539
+
540
+ test "something that needs versioning" do
541
+ with_versioning do
542
+ # your test
543
+ end
544
+ end
545
+
546
+ ### Per request
547
+
548
+ You can turn PaperTrail on or off per request by adding a `paper_trail_enabled_for_controller` method to your controller which returns true or false:
549
+
550
+ class ApplicationController < ActionController::Base
551
+ def paper_trail_enabled_for_controller
552
+ request.user_agent != 'Disable User-Agent'
553
+ end
554
+ end
555
+
556
+ ### Per class
557
+
558
+ If you are about change some widgets and you don't want a paper trail of your changes, you can turn PaperTrail off like this:
559
+
560
+ >> Widget.paper_trail_off
561
+
562
+ And on again like this:
563
+
564
+ >> Widget.paper_trail_on
565
+
566
+ ### Per method call
567
+
568
+ You can call a method without creating a new version using `without_versioning`. It takes either a method name as a symbol:
569
+
570
+ @widget.without_versioning :destroy
571
+
572
+ Or a block:
573
+
574
+ @widget.without_versioning do
575
+ @widget.update_attributes :name => 'Ford'
576
+ end
577
+
578
+
579
+ ## Deleting Old Versions
580
+
581
+ Over time your `versions` table will grow to an unwieldy size. Because each version is self-contained (see the Diffing section above for more) you can simply delete any records you don't want any more. For example:
582
+
583
+ sql> delete from versions where created_at < 2010-06-01;
584
+
585
+ >> Version.delete_all ["created_at < ?", 1.week.ago]
586
+
587
+
588
+ ## Installation
589
+
590
+ ### Rails 3
591
+
592
+ 1. Install PaperTrail as a gem via your `Gemfile`:
593
+
594
+ `gem 'paper_trail', '~> 2'`
595
+
596
+ 2. Generate a migration which will add a `versions` table to your database.
597
+
598
+ `bundle exec rails generate paper_trail:install`
599
+
600
+ 3. Run the migration.
601
+
602
+ `bundle exec rake db:migrate`
603
+
604
+ 4. Add `has_paper_trail` to the models you want to track.
605
+
606
+ ### Rails 2
607
+
608
+ Please see the `rails2` branch.
609
+
610
+
611
+ ## Testing
612
+
613
+ PaperTrail uses Bundler to manage its dependencies (in development and testing). You can run the tests with `bundle exec rake test`. (You may need to `bundle install` first.)
614
+
615
+
616
+ ## Articles
617
+
618
+ [Keep a Paper Trail with PaperTrail](http://www.linux-mag.com/id/7528), Linux Magazine, 16th September 2009.
619
+
620
+
621
+ ## Problems
622
+
623
+ Please use GitHub's [issue tracker](http://github.com/airblade/paper_trail/issues).
624
+
625
+
626
+ ## Contributors
627
+
628
+ Many thanks to:
629
+
630
+ * [Zachery Hostens](http://github.com/zacheryph)
631
+ * [Jeremy Weiskotten](http://github.com/jeremyw)
632
+ * [Phan Le](http://github.com/revo)
633
+ * [jdrucza](http://github.com/jdrucza)
634
+ * [conickal](http://github.com/conickal)
635
+ * [Thibaud Guillaume-Gentil](http://github.com/thibaudgg)
636
+ * Danny Trelogan
637
+ * [Mikl Kurkov](http://github.com/mkurkov)
638
+ * [Franco Catena](https://github.com/francocatena)
639
+ * [Emmanuel Gomez](https://github.com/emmanuel)
640
+ * [Matthew MacLeod](https://github.com/mattmacleod)
641
+ * [benzittlau](https://github.com/benzittlau)
642
+ * [Tom Derks](https://github.com/EgoH)
643
+ * [Jonas Hoglund](https://github.com/jhoglund)
644
+ * [Stefan Huber](https://github.com/MSNexploder)
645
+ * [thinkcast](https://github.com/thinkcast)
646
+ * [Dominik Sander](https://github.com/dsander)
647
+ * [Burke Libbey](https://github.com/burke)
648
+ * [6twenty](https://github.com/6twenty)
649
+ * [nir0](https://github.com/nir0)
650
+ * [Eduard Tsech](https://github.com/edtsech)
651
+ * [Mathieu Arnold](https://github.com/mat813)
652
+
653
+
654
+ ## Inspirations
655
+
656
+ * [Simply Versioned](http://github.com/github/simply_versioned)
657
+ * [Acts As Audited](http://github.com/collectiveidea/acts_as_audited)
658
+
659
+
660
+ ## Intellectual Property
661
+
662
+ Copyright (c) 2011 Andy Stewart (boss@airbladesoftware.com).
663
+ Released under the MIT licence.