From d7f3b1759888fe72380dbc40a1a6946c9e8b47cb Mon Sep 17 00:00:00 2001 From: Mehrez Alachheb Date: Mon, 26 May 2014 17:58:52 +0200 Subject: [PATCH 1/2] Add version_at method --- lib/mongoid/history/trackable.rb | 10 ++++++++++ spec/integration/integration_spec.rb | 23 +++++++++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/lib/mongoid/history/trackable.rb b/lib/mongoid/history/trackable.rb index 786ed2d2..d7f21232 100644 --- a/lib/mongoid/history/trackable.rb +++ b/lib/mongoid/history/trackable.rb @@ -84,6 +84,16 @@ def undo!(modifier = nil, options_or_version = nil) save! end + def version_at(year, month = nil, day = nil, hour = nil, minute = nil, second = nil) + at = Time.new(year, month, day, hour, minute, second) + duplicate = self.dup + history_tracks.where(:created_at.gt => at, action: "update").desc(:version).map do |h| + undo_attr = h.undo_attr(modifier) + duplicate.attributes.merge!(undo_attr) + end + duplicate + end + def redo!(modifier = nil, options_or_version = nil) versions = get_versions_criteria(options_or_version).to_a versions.sort! { |v1, v2| v1.version <=> v2.version } diff --git a/spec/integration/integration_spec.rb b/spec/integration/integration_spec.rb index abc44536..228e690c 100644 --- a/spec/integration/integration_spec.rb +++ b/spec/integration/integration_spec.rb @@ -619,6 +619,29 @@ class Foo < Comment end end + describe "version_at" do + before :each do + [Time.new(2014,01,01), Time.new(2014,01,02), Time.new(2014,01,03), Time.new(2014,01,04) ].each_with_index do |time, index| + post.history_tracks.create(created_at: time, + association_chain: [{"name"=>"Post", "id"=> post.id}], + modified: {"title"=>"Test #{index + 1}"}, + original: {"title"=>"Test #{index}"}, + version: index+1, + action: "update", + scope: "post", + modifier_id: user.id) + end + end + + it "should get version_at" do + post.version_at(2013,12,31).title.should == "Test 0" + post.version_at(2014,01,01,12).title.should == "Test 1" + post.version_at(2014,01,02).title.should == "Test 2" + post.version_at(2014,01,03,23,59,59).title.should == "Test 3" + end + + end + describe "trackables" do before :each do comment.update_attributes(title: "Test2") # version == 2 From 40b94b12f5462122b0fc6844e48b98eb85642b07 Mon Sep 17 00:00:00 2001 From: Mehrez Alachheb Date: Mon, 26 May 2014 18:04:29 +0200 Subject: [PATCH 2/2] Add version_at sample in README --- README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/README.md b/README.md index b0a7f78a..b0c13337 100644 --- a/README.md +++ b/README.md @@ -140,6 +140,9 @@ post.destroy # undelete post post.undo! user +# post version at +post.version_at(yyyy, mm, dd, hh, min, sec) + # disable tracking for comments within a block Comment.disable_tracking do comment.update_attributes(:title => "Test 3")