bitfluent-vestal_versions 1.1.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (42) hide show
  1. data/.gitignore +23 -0
  2. data/LICENSE +20 -0
  3. data/README.rdoc +175 -0
  4. data/Rakefile +45 -0
  5. data/VERSION +1 -0
  6. data/generators/vestal_versions/templates/initializer.rb +9 -0
  7. data/generators/vestal_versions/templates/migration.rb +27 -0
  8. data/generators/vestal_versions/vestal_versions_generator.rb +24 -0
  9. data/init.rb +1 -0
  10. data/lib/vestal_versions.rb +103 -0
  11. data/lib/vestal_versions/changes.rb +125 -0
  12. data/lib/vestal_versions/conditions.rb +69 -0
  13. data/lib/vestal_versions/configuration.rb +40 -0
  14. data/lib/vestal_versions/control.rb +175 -0
  15. data/lib/vestal_versions/creation.rb +100 -0
  16. data/lib/vestal_versions/options.rb +45 -0
  17. data/lib/vestal_versions/reload.rb +23 -0
  18. data/lib/vestal_versions/reset.rb +28 -0
  19. data/lib/vestal_versions/reversion.rb +69 -0
  20. data/lib/vestal_versions/tagging.rb +50 -0
  21. data/lib/vestal_versions/users.rb +57 -0
  22. data/lib/vestal_versions/version.rb +32 -0
  23. data/lib/vestal_versions/versioned.rb +30 -0
  24. data/lib/vestal_versions/versions.rb +74 -0
  25. data/test/changes_test.rb +169 -0
  26. data/test/conditions_test.rb +137 -0
  27. data/test/configuration_test.rb +39 -0
  28. data/test/control_test.rb +152 -0
  29. data/test/creation_test.rb +148 -0
  30. data/test/options_test.rb +52 -0
  31. data/test/reload_test.rb +19 -0
  32. data/test/reset_test.rb +112 -0
  33. data/test/reversion_test.rb +68 -0
  34. data/test/schema.rb +43 -0
  35. data/test/tagging_test.rb +39 -0
  36. data/test/test_helper.rb +12 -0
  37. data/test/users_test.rb +25 -0
  38. data/test/version_test.rb +43 -0
  39. data/test/versioned_test.rb +18 -0
  40. data/test/versions_test.rb +172 -0
  41. data/vestal_versions.gemspec +105 -0
  42. metadata +167 -0
data/.gitignore ADDED
@@ -0,0 +1,23 @@
1
+ ## MAC OS
2
+ .DS_Store
3
+
4
+ ## TEXTMATE
5
+ *.tmproj
6
+ tmtags
7
+
8
+ ## EMACS
9
+ *~
10
+ \#*
11
+ .\#*
12
+
13
+ ## VIM
14
+ *.swp
15
+
16
+ ## PROJECT::GENERAL
17
+ coverage
18
+ rdoc
19
+ pkg
20
+
21
+ ## PROJECT::SPECIFIC
22
+ *.db
23
+ .rvmrc
data/LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ Copyright (c) 2009 Steve Richert
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.rdoc ADDED
@@ -0,0 +1,175 @@
1
+ = vestal_versions for Rails 3
2
+
3
+ Finally, DRY ActiveRecord versioning!
4
+
5
+ <tt>acts_as_versioned</tt>[http://github.com/technoweenie/acts_as_versioned] by technoweenie[http://github.com/technoweenie] was a great start, but it failed to keep up with ActiveRecord's introduction of dirty objects in version 2.1. Additionally, each versioned model needs its own versions table that duplicates most of the original table's columns. The versions table is then populated with records that often duplicate most of the original record's attributes. All in all, not very DRY.
6
+
7
+ <tt>vestal_versions</tt>[http://github.com/laserlemon/vestal_versions] requires only one versions table (polymorphically associated with its parent models) and no changes whatsoever to existing tables. But it goes one step DRYer by storing a serialized hash of _only_ the models' changes. Think modern version control systems. By traversing the record of changes, the models can be reverted to any point in time.
8
+
9
+ And that's just what <tt>vestal_versions</tt> does. Not only can a model be reverted to a previous version number but also to a date or time!
10
+
11
+ == Compatibility
12
+
13
+ Tested with Active Record 3.0.0.beta4 with Ruby 1.8.7 and 1.9.2-preview3.
14
+
15
+ == Installation
16
+
17
+ In the Gemfile:
18
+
19
+ gem 'vestal_versions', :git => 'git://github.com/lailsonbm/vestal_versions', :branch => 'rails3'
20
+
21
+ Next, generate and run the first and last versioning migration you'll ever need:
22
+
23
+ $ rails generate vestal_versions
24
+ $ rake db:migrate
25
+
26
+ == Example
27
+
28
+ To version an ActiveRecord model, simply add <tt>versioned</tt> to your class like so:
29
+
30
+ class User < ActiveRecord::Base
31
+ versioned
32
+
33
+ validates_presence_of :first_name, :last_name
34
+
35
+ def name
36
+ "#{first_name} #{last_name}"
37
+ end
38
+ end
39
+
40
+ It's that easy! Now watch it in action...
41
+
42
+ >> u = User.create(:first_name => "Steve", :last_name => "Richert")
43
+ => #<User first_name: "Steve", last_name: "Richert">
44
+ >> u.version
45
+ => 1
46
+ >> u.update_attribute(:first_name, "Stephen")
47
+ => true
48
+ >> u.name
49
+ => "Stephen Richert"
50
+ >> u.version
51
+ => 2
52
+ >> u.revert_to(10.seconds.ago)
53
+ => 1
54
+ >> u.name
55
+ => "Steve Richert"
56
+ >> u.version
57
+ => 1
58
+ >> u.save
59
+ => true
60
+ >> u.version
61
+ => 3
62
+ >> u.update_attribute(:last_name, "Jobs")
63
+ => true
64
+ >> u.name
65
+ => "Steve Jobs"
66
+ >> u.version
67
+ => 4
68
+ >> u.revert_to!(2)
69
+ => true
70
+ >> u.name
71
+ => "Stephen Richert"
72
+ >> u.version
73
+ => 5
74
+
75
+ == Upgrading to 1.0
76
+
77
+ For the most part, version 1.0 of <tt>vestal_versions</tt> is backwards compatible, with just a few notable changes:
78
+
79
+ * The versions table has been beefed up. You'll need to add the following columns (and indexes, if you feel so inclined):
80
+
81
+ change_table :versions do |t|
82
+ t.belongs_to :user, :polymorphic => true
83
+ t.string :user_name
84
+ t.string :tag
85
+ end
86
+
87
+ change_table :versions do |t|
88
+ t.index [:user_id, :user_type]
89
+ t.index :user_name
90
+ t.index :tag
91
+ end
92
+
93
+ * When a model is created (or updated the first time after being versioned), an initial version record with a number of 1 is no longer created. These aren't used during reversion and so they end up just being dead weight. Feel free to scrap all your versions where <tt>number == 1</tt> after the upgrade if you'd like to free up some room in your database (but you don't have to).
94
+
95
+ * Models that have no version records in the database will return a <tt>@user.version</tt> of 1. In the past, this would have returned <tt>nil</tt> instead.
96
+
97
+ * <tt>Version</tt> has moved to <tt>VestalVersions::Version</tt> to make way for custom version classes.
98
+
99
+ * <tt>Version#version</tt> did not survive the move to <tt>VestalVersions::Version#version</tt>. That alias was dropped (too confusing). Use <tt>VestalVersions::Version#number</tt>.
100
+
101
+ == New to 1.0
102
+
103
+ There are a handful of exciting new additions in version 1.0 of <tt>vestal_versions</tt>. A lot has changed in the code: much better documentation, more modular organization of features, and a more exhaustive test suite. But there are also a number of new features that are available in this release of <tt>vestal_versions</tt>:
104
+
105
+ * The ability to completely skip versioning within a new <tt>skip_version</tt> block:
106
+
107
+ @user.version # => 1
108
+ @user.skip_version do
109
+ @user.update_attribute(:first_name, "Stephen")
110
+ @user.first_name = "Steve"
111
+ @user.save
112
+ @user.update_attributes(:last_name => "Jobs")
113
+ end
114
+ @user.version # => 1
115
+
116
+ Also available, are <tt>merge_version</tt> and <tt>append_version</tt> blocks. The <tt>merge_version</tt> block will compile the possibly multiple versions that would result from the updates inside the block into one summary version. The single resulting version is then tacked onto the version history as usual. The <tt>append_version</tt> block works similarly except that the resulting single version is combined with the most recent version in the history and saved.
117
+
118
+ * Version tagging. Any version can have a tag attached to it (must be unique within the scope of the versioned parent) and that tag can be used for reversion.
119
+
120
+ @user.name # => "Steve Richert"
121
+ @user.update_attribute(:last_name, "Jobs")
122
+ @user.name # => "Steve Jobs"
123
+ @user.tag_version("apple")
124
+ @user.update_attribute(:last_name, "Richert")
125
+ @user.name # => "Steve Richert"
126
+ @user.revert_to("apple")
127
+ @user.name # => "Steve Jobs"
128
+
129
+ So if you're not big on version numbers, you could just tag your versions and avoid the numbers altogether.
130
+
131
+ * Resetting. This is basically a hard revert. The new <tt>reset_to!</tt> instance method behaves just like the <tt>revert_to!</tt> method except that after the reversion, it will also scrap all the versions that came after that target version.
132
+
133
+ @user.name # => "Steve Richert"
134
+ @user.version # => 1
135
+ @user.versions.count # => 0
136
+ @user.update_attribute(:last_name, "Jobs")
137
+ @user.name # => "Steve Jobs"
138
+ @user.version # => 2
139
+ @user.versions.count # => 1
140
+ @user.reset_to!(1)
141
+ @user.name # => "Steve Richert"
142
+ @user.version # => 1
143
+ @user.versions.count # => 0
144
+
145
+ * Storing which user is responsible for a revision. Rather than introduce a lot of controller magic to guess what to store, you can simply update an additional attribute on your versioned model: <tt>updated_by</tt>.
146
+
147
+ @user.update_attributes(:last_name => "Jobs", :updated_by => "Tyler")
148
+ @user.versions.last.user # => "Tyler"
149
+
150
+ Instead of passing a simple string to the <tt>updated_by</tt> setter, you can pass a model instance, such as an ActiveRecord user or administrator. The association will be saved polymorphically alongside the version.
151
+
152
+ @user.update_attributes(:last_name => "Jobs", :updated_by => current_user)
153
+ @user.versions.last.user # => #<User first_name: "Steven", last_name: "Tyler">
154
+
155
+ * Global configuration. The new <tt>vestal_versions</tt> Rails generator also writes an initializer with instructions on how to set application-wide options for the <tt>versioned</tt> method.
156
+
157
+ * Conditional version creation. The <tt>versioned</tt> method now accepts <tt>:if</tt> and <tt>:unless</tt> options. Each expects a symbol representing an instance method or a proc that will be evaluated to determine whether or not to create a new version after an update. An array containing any combination of symbols and procs can also be given.
158
+
159
+ class User < ActiveRecord::Base
160
+ versioned :if => :really_create_a_version?
161
+ end
162
+
163
+ * Custom version classes. By passing a <tt>:class_name</tt> option to the <tt>versioned</tt> method, you can specify your own ActiveRecord version model. <tt>VestalVersions::Version</tt> is the default, but feel free to stray from that. I recommend that your custom model inherit from <tt>VestalVersions::Version</tt>, but that's up to you!
164
+
165
+ * A <tt>versioned?</tt> convenience class method. If your user model is versioned, <tt>User.versioned?</tt> will let you know.
166
+
167
+ == Thanks!
168
+
169
+ Thank you to all those who post {issues and suggestions}[http://github.com/laserlemon/vestal_versions/issues]. And special thanks to:
170
+
171
+ * splattael[http://github.com/splattael], who first bugged (and helped) me to write some tests for this thing
172
+ * snaury[http://github.com/snaury], who helped out early on with the <tt>between</tt> association method, the <tt>:dependent</tt> option and a conflict from using a method called <tt>changes</tt>
173
+ * sthapit[http://github.com/sthapit], who was responsible for the <tt>:only</tt> and <tt>:except</tt> options as well as showing me that I'm a dummy for storing a useless first version
174
+
175
+ To contribute to <tt>vestal_versions</tt>, please fork, hack away in the integration[http://github.com/laserlemon/vestal_versions/tree/integration] branch and send me a pull request. Remember your tests!
data/Rakefile ADDED
@@ -0,0 +1,45 @@
1
+ require 'rubygems'
2
+ require 'rake'
3
+ require 'rake/testtask'
4
+ require 'rcov/rcovtask'
5
+ require 'rake/rdoctask'
6
+
7
+ begin
8
+ require 'jeweler'
9
+ Jeweler::Tasks.new do |g|
10
+ g.name = 'vestal_versions'
11
+ g.summary = %(Keep a DRY history of your ActiveRecord models' changes)
12
+ g.description = %(Keep a DRY history of your ActiveRecord models' changes)
13
+ g.email = 'steve@laserlemon.com'
14
+ g.homepage = 'http://github.com/laserlemon/vestal_versions'
15
+ g.authors = %w(laserlemon)
16
+ g.add_dependency 'activerecord', '>= 3.0.0.beta4'
17
+ g.add_development_dependency 'shoulda'
18
+ g.add_development_dependency 'mocha'
19
+ end
20
+ Jeweler::GemcutterTasks.new
21
+ rescue LoadError
22
+ puts 'Jeweler (or a dependency) not available. Install it with: sudo gem install jeweler'
23
+ end
24
+
25
+ Rake::TestTask.new do |t|
26
+ t.libs = %w(test)
27
+ t.pattern = 'test/**/*_test.rb'
28
+ end
29
+
30
+ Rcov::RcovTask.new do |t|
31
+ t.libs = %w(test)
32
+ t.pattern = 'test/**/*_test.rb'
33
+ end
34
+
35
+ task :test => :check_dependencies
36
+ task :default => :test
37
+
38
+ Rake::RDocTask.new do |r|
39
+ version = File.exist?('VERSION') ? File.read('VERSION') : nil
40
+ r.rdoc_dir = 'rdoc'
41
+ r.title = ['vestal_versions', version].compact.join(' ')
42
+ r.options << '--line-numbers' << '--inline-source'
43
+ r.rdoc_files.include('README*')
44
+ r.rdoc_files.include('lib/**/*.rb')
45
+ end
data/VERSION ADDED
@@ -0,0 +1 @@
1
+ 1.1.0
@@ -0,0 +1,9 @@
1
+ VestalVersions.configure do |config|
2
+ # Place any global options here. For example, in order to specify your own version model to use
3
+ # throughout the application, simply specify:
4
+ #
5
+ # config.class_name = "MyCustomVersion"
6
+ #
7
+ # Any options passed to the "versioned" method in the model itself will override this global
8
+ # configuration.
9
+ end
@@ -0,0 +1,27 @@
1
+ class CreateVestalVersions < ActiveRecord::Migration
2
+ def self.up
3
+ create_table :versions do |t|
4
+ t.belongs_to :versioned, :polymorphic => true
5
+ t.belongs_to :user, :polymorphic => true
6
+ t.string :user_name
7
+ t.text :modifications
8
+ t.integer :number
9
+ t.string :tag
10
+
11
+ t.timestamps
12
+ end
13
+
14
+ change_table :versions do |t|
15
+ t.index [:versioned_id, :versioned_type]
16
+ t.index [:user_id, :user_type]
17
+ t.index :user_name
18
+ t.index :number
19
+ t.index :tag
20
+ t.index :created_at
21
+ end
22
+ end
23
+
24
+ def self.down
25
+ drop_table :versions
26
+ end
27
+ end
@@ -0,0 +1,24 @@
1
+ require 'rails/generators'
2
+
3
+ class VestalVersionsGenerator < Rails::Generators::NamedBase
4
+ include Rails::Generators::Migration
5
+
6
+ argument :name, :type => :string, :default => "create_vestal_versions"
7
+ source_root File.expand_path('../templates', __FILE__)
8
+
9
+ def generate_files
10
+ migration_template 'migration.rb', File.join('db', 'migrate', 'create_vestal_versions')
11
+ template 'initializer.rb', File.join('config', 'initializers', 'vestal_versions.rb')
12
+ end
13
+
14
+ protected
15
+ # Lets make this hacky thing while ticket #3820 isn't applied again...
16
+ # https://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets/3820
17
+ def self.next_migration_number(dirname) #:nodoc:
18
+ orm = Rails.configuration.generators.options[:rails][:orm]
19
+ require "rails/generators/#{orm}"
20
+ "#{orm.to_s.camelize}::Generators::Base".constantize.next_migration_number(dirname)
21
+ rescue
22
+ raise NotImplementedError
23
+ end
24
+ end
data/init.rb ADDED
@@ -0,0 +1 @@
1
+ require File.join(File.dirname(__FILE__), 'lib', 'vestal_versions')
@@ -0,0 +1,103 @@
1
+ # +vestal_versions+ keeps track of updates to ActiveRecord models, leveraging the introduction of
2
+ # dirty attributes in Rails 2.1. By storing only the updated attributes in a serialized column of a
3
+ # single version model, the history is kept DRY and no additional schema changes are necessary.
4
+ #
5
+ # Author:: Steve Richert
6
+ # Copyright:: Copyright (c) 2009 Steve Richert
7
+ # License:: MIT License (http://www.opensource.org/licenses/mit-license.php)
8
+ #
9
+ # To enable versioning on a model, simply use the +versioned+ method:
10
+ #
11
+ # class User < ActiveRecord::Base
12
+ # versioned
13
+ # end
14
+ #
15
+ # user = User.create(:name => "Steve Richert")
16
+ # user.version # => 1
17
+ # user.update_attribute(:name, "Steve Jobs")
18
+ # user.version # => 2
19
+ # user.revert_to(1)
20
+ # user.name # => "Steve Richert"
21
+ #
22
+ # See the +versioned+ documentation for more details.
23
+
24
+ require File.expand_path(File.join(File.dirname(__FILE__), '..', 'generators', 'vestal_versions', 'vestal_versions_generator'))
25
+ Dir[File.join(File.dirname(__FILE__), 'vestal_versions', '*.rb')].each{|f| require f }
26
+
27
+ # The base module that gets included in ActiveRecord::Base. See the documentation for
28
+ # VestalVersions::ClassMethods for more useful information.
29
+ module VestalVersions
30
+ def self.included(base) # :nodoc:
31
+ base.class_eval do
32
+ extend ClassMethods
33
+ extend Versioned
34
+ end
35
+ end
36
+
37
+ module ClassMethods
38
+ # +versioned+ associates an ActiveRecord model with many versions. When the object is updated,
39
+ # a new version containing the changes is created. There are several options available to the
40
+ # +versioned+ method, most of which are passed to the +has_many+ association itself:
41
+ # * <tt>:class_name</tt>: The class name of the version model to use for the association. By
42
+ # default, this is set to "VestalVersions::Version", representing the built-in version class.
43
+ # By specifying this option, you can override the version class, to include custom version
44
+ # behavior. It's recommended that a custom version inherit from VestalVersions::Version.
45
+ # * <tt>:dependent</tt>: Also common to +has_many+ associations, this describes the behavior of
46
+ # version records when the parent object is destroyed. This defaults to :delete_all, which
47
+ # will permanently remove all associated versions *without* triggering any destroy callbacks.
48
+ # Other options are :destroy which removes the associated versions *with* callbacks, or
49
+ # :nullify which leaves the version records in the database, but dissociates them from the
50
+ # parent object by setting the foreign key columns to +nil+ values.
51
+ # * <tt>:except</tt>: An update will trigger version creation as long as at least one column
52
+ # outside those specified here was updated. Also, upon version creation, the columns
53
+ # specified here will be excluded from the change history. This is useful when dealing with
54
+ # unimportant, constantly changing, or sensitive information. This option accepts a symbol,
55
+ # string or an array of either, representing column names to exclude. It is completely
56
+ # optional and defaults to +nil+, allowing all columns to be versioned. This option is also
57
+ # ignored if the +only+ option is used.
58
+ # * <tt>:extend</tt>: This option allows you to extend the +has_many+ association proxy with a
59
+ # module or an array of modules. Any methods defined in those modules become available on the
60
+ # +versions+ association. The VestalVersions::Versions module is essential to the
61
+ # functionality of +vestal_versions+ and so is prepended to any additional modules that you
62
+ # might specify here.
63
+ # * <tt>:if</tt>: Accepts a symbol, a proc or an array of either to be evaluated when the parent
64
+ # object is updated to determine whether a new version should be created. +to_proc+ is called
65
+ # on any symbols given and the resulting procs are called, passing in the object itself. If
66
+ # an array is given, all must be evaluate to +true+ in order for a version to be created.
67
+ # * <tt>:initial_version</tt>: When set to true, an initial version is always created when the
68
+ # parent object is created. This initial version will have nil changes however it can be
69
+ # used to store who created the original version.
70
+ # * <tt>:only</tt>: An update will trigger version creation as long as at least one updated
71
+ # column falls within those specified here. Also, upon version creation, only the columns
72
+ # specified here will be included in the change history. This option accepts a symbol, string
73
+ # or an array of either, representing column names to include. It is completely optional and
74
+ # defaults to +nil+, allowing all columns to be versioned. This option takes precedence over
75
+ # the +except+ option if both are specified.
76
+ # * <tt>:unless</tt>: Accepts a symbol, a proc or an array of either to be evaluated when the
77
+ # parent object is updated to determine whether version creation should be skipped. +to_proc+
78
+ # is called on any symbols given and the resulting procs are called, passing in the object
79
+ # itself. If an array is given and any element evaluates as +true+, the version creation will
80
+ # be skipped.
81
+ def versioned(options = {}, &block)
82
+ return if versioned?
83
+
84
+ include Options
85
+ include Changes
86
+ include Creation
87
+ include Users
88
+ include Reversion
89
+ include Reset
90
+ include Conditions
91
+ include Control
92
+ include Tagging
93
+ include Reload
94
+
95
+ prepare_versioned_options(options)
96
+ has_many :versions, options, &block
97
+ end
98
+ end
99
+
100
+ extend Configuration
101
+ end
102
+
103
+ ActiveRecord::Base.send(:include, VestalVersions)
@@ -0,0 +1,125 @@
1
+ module VestalVersions
2
+ # Provides the ability to manipulate hashes in the specific format that ActiveRecord gives to
3
+ # dirty attribute changes: string keys and unique, two-element array values.
4
+ module Changes
5
+ def self.included(base) # :nodoc:
6
+ Hash.send(:include, HashMethods)
7
+
8
+ base.class_eval do
9
+ include InstanceMethods
10
+
11
+ after_update :merge_version_changes
12
+ end
13
+ end
14
+
15
+ # Methods available to versioned ActiveRecord::Base instances in order to manage changes used
16
+ # for version creation.
17
+ module InstanceMethods
18
+ # Collects an array of changes from a record's versions between the given range and compiles
19
+ # them into one summary hash of changes. The +from+ and +to+ arguments can each be either a
20
+ # version number, a symbol representing an association proxy method, a string representing a
21
+ # version tag or a version object itself.
22
+ def changes_between(from, to)
23
+ from_number, to_number = versions.number_at(from), versions.number_at(to)
24
+ return {} if from_number == to_number
25
+ chain = versions.between(from_number, to_number).reject(&:initial?)
26
+ return {} if chain.empty?
27
+
28
+ backward = from_number > to_number
29
+ backward ? chain.pop : chain.shift unless from_number == 1 || to_number == 1
30
+
31
+ chain.inject({}) do |changes, version|
32
+ changes.append_changes!(backward ? version.changes.reverse_changes : version.changes)
33
+ end
34
+ end
35
+
36
+ private
37
+ # Before a new version is created, the newly-changed attributes are appended onto a hash
38
+ # of previously-changed attributes. Typically the previous changes will be empty, except in
39
+ # the case that a control block is used where versions are to be merged. See
40
+ # VestalVersions::Control for more information.
41
+ def merge_version_changes
42
+ version_changes.append_changes!(incremental_version_changes)
43
+ end
44
+
45
+ # Stores the cumulative changes that are eventually used for version creation.
46
+ def version_changes
47
+ @version_changes ||= {}
48
+ end
49
+
50
+ # Stores the incremental changes that are appended to the cumulative changes before version
51
+ # creation. Incremental changes are reset when the record is saved because they represent
52
+ # a subset of the dirty attribute changes, which are reset upon save.
53
+ def incremental_version_changes
54
+ changes.slice(*versioned_columns)
55
+ end
56
+
57
+ # Simply resets the cumulative changes after version creation.
58
+ def reset_version_changes
59
+ @version_changes = nil
60
+ end
61
+ end
62
+
63
+ # Instance methods included into Hash for dealing with manipulation of hashes in the specific
64
+ # format of ActiveRecord::Base#changes.
65
+ module HashMethods
66
+ # When called on a hash of changes and given a second hash of changes as an argument,
67
+ # +append_changes+ will run the second hash on top of the first, updating the last element
68
+ # of each array value with its own, or creating its own key/value pair for missing keys.
69
+ # Resulting non-unique array values are removed.
70
+ #
71
+ # == Example
72
+ #
73
+ # first = {
74
+ # "first_name" => ["Steve", "Stephen"],
75
+ # "age" => [25, 26]
76
+ # }
77
+ # second = {
78
+ # "first_name" => ["Stephen", "Steve"],
79
+ # "last_name" => ["Richert", "Jobs"],
80
+ # "age" => [26, 54]
81
+ # }
82
+ # first.append_changes(second)
83
+ # # => {
84
+ # "last_name" => ["Richert", "Jobs"],
85
+ # "age" => [25, 54]
86
+ # }
87
+ def append_changes(changes)
88
+ changes.inject(self) do |new_changes, (attribute, change)|
89
+ new_change = [new_changes.fetch(attribute, change).first, change.last]
90
+ new_changes.merge(attribute => new_change)
91
+ end.reject do |attribute, change|
92
+ change.first == change.last
93
+ end
94
+ end
95
+
96
+ # Destructively appends a given hash of changes onto an existing hash of changes.
97
+ def append_changes!(changes)
98
+ replace(append_changes(changes))
99
+ end
100
+
101
+ # Appends the existing hash of changes onto a given hash of changes. Relates to the
102
+ # +append_changes+ method in the same way that Hash#reverse_merge relates to
103
+ # Hash#merge.
104
+ def prepend_changes(changes)
105
+ changes.append_changes(self)
106
+ end
107
+
108
+ # Destructively prepends a given hash of changes onto an existing hash of changes.
109
+ def prepend_changes!(changes)
110
+ replace(prepend_changes(changes))
111
+ end
112
+
113
+ # Reverses the array values of a hash of changes. Useful for reversion both backward and
114
+ # forward through a record's history of changes.
115
+ def reverse_changes
116
+ inject({}){|nc,(a,c)| nc.merge!(a => c.reverse) }
117
+ end
118
+
119
+ # Destructively reverses the array values of a hash of changes.
120
+ def reverse_changes!
121
+ replace(reverse_changes)
122
+ end
123
+ end
124
+ end
125
+ end