From aa00ccae0229ed9f4e81ec0fec053a560dc435f4 Mon Sep 17 00:00:00 2001 From: Andy Stewart Date: Thu, 21 Oct 2010 12:30:50 +0100 Subject: [PATCH] Add convenience method to find out if instance is live. --- README.md | 7 +++++++ lib/paper_trail/has_paper_trail.rb | 6 ++++++ test/paper_trail_model_test.rb | 15 +++++++++++++-- 3 files changed, 26 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 28caaf79..c99e36f4 100644 --- a/README.md +++ b/README.md @@ -171,6 +171,13 @@ Finally, if you got an item by reifying one of its versions, you can navigate ba >> widget = latest_version.reify >> widget.version == latest_version # true +You can find out whether a model instance is the current, live one -- or whether it came instead from a previous version -- with `live?`: + + >> widget = Widget.find 42 + >> widget.live? # true + >> widget = widget.versions.last.reify + >> widget.live? # false + ## Finding Out Who Was Responsible For A Change diff --git a/lib/paper_trail/has_paper_trail.rb b/lib/paper_trail/has_paper_trail.rb index 3e135717..ad9f0d7d 100644 --- a/lib/paper_trail/has_paper_trail.rb +++ b/lib/paper_trail/has_paper_trail.rb @@ -78,6 +78,12 @@ module PaperTrail end end + # Returns true if this instance is the current, live one; + # returns false if this instance came from a previous version. + def live? + version.nil? + end + # Returns who put the object into its current state. def originator versions.last.try :whodunnit diff --git a/test/paper_trail_model_test.rb b/test/paper_trail_model_test.rb index 7c10e6b5..68fa28b2 100644 --- a/test/paper_trail_model_test.rb +++ b/test/paper_trail_model_test.rb @@ -46,8 +46,7 @@ end class HasPaperTrailModelTest < Test::Unit::TestCase load_schema -=begin -=end + context 'A record' do setup { @article = Article.create } @@ -70,6 +69,10 @@ class HasPaperTrailModelTest < Test::Unit::TestCase assert_equal [], @widget.versions end + should 'be live' do + assert @widget.live? + end + context 'which is then created' do setup { @widget.update_attributes :name => 'Henry' } @@ -87,6 +90,10 @@ class HasPaperTrailModelTest < Test::Unit::TestCase assert_match /create/i, @widget.versions.first.event end + should 'be live' do + assert @widget.live? + end + context 'and then updated without any changes' do setup { @widget.save } @@ -120,6 +127,10 @@ class HasPaperTrailModelTest < Test::Unit::TestCase assert_match /update/i, @widget.versions.last.event end + should 'have versions that are not live' do + assert @widget.versions.map(&:reify).compact.all? { |w| !w.live? } + end + context 'and has one associated object' do setup do