acts_as_versioned upgrade.

git-svn-id: http://redmine.rubyforge.org/svn/branches/work@1471 e93f8b46-1217-0410-a6f0-8f06a7374b81
This commit is contained in:
Jean-Philippe Lang committed 2008-05-27 18:35:28 +00:00
1 parent 5f108dfb0f
commit 8a39707f1c
5 files changed
+186 -84

No files matched your search

@@ -22,7 +22,7 @@
module ActiveRecord #:nodoc: module ActiveRecord #:nodoc:
module Acts #:nodoc: module Acts #:nodoc:
# Specify this act if you want to save a copy of the row in a versioned table. This assumes there is a # Specify this act if you want to save a copy of the row in a versioned table. This assumes there is a
# versioned table ready and that your model has a version field. This works with optimisic locking if the lock_version # versioned table ready and that your model has a version field. This works with optimistic locking if the lock_version
# column is present as well. # column is present as well.
# #
# The class for the versioned model is derived the first time it is seen. Therefore, if you change your database schema you have to restart # The class for the versioned model is derived the first time it is seen. Therefore, if you change your database schema you have to restart
@@ -49,9 +49,24 @@ module ActiveRecord #:nodoc:
# page.revert_to(page.versions.last) # using versioned instance # page.revert_to(page.versions.last) # using versioned instance
# page.title # => 'hello world' # page.title # => 'hello world'
# #
# page.versions.earliest # efficient query to find the first version
# page.versions.latest # efficient query to find the most recently created version
#
#
# Simple Queries to page between versions
#
# page.versions.before(version)
# page.versions.after(version)
#
# Access the previous/next versions from the versioned model itself
#
# version = page.versions.latest
# version.previous # go back one version
# version.next # go forward one version
#
# See ActiveRecord::Acts::Versioned::ClassMethods#acts_as_versioned for configuration options # See ActiveRecord::Acts::Versioned::ClassMethods#acts_as_versioned for configuration options
module Versioned module Versioned
CALLBACKS = [:set_new_version, :save_version_on_create, :save_version?, :clear_changed_attributes] CALLBACKS = [:set_new_version, :save_version_on_create, :save_version?, :clear_altered_attributes]
def self.included(base) # :nodoc: def self.included(base) # :nodoc:
base.extend ClassMethods base.extend ClassMethods
end end
@@ -159,7 +174,7 @@ module ActiveRecord #:nodoc:
send :include, ActiveRecord::Acts::Versioned::ActMethods send :include, ActiveRecord::Acts::Versioned::ActMethods
cattr_accessor :versioned_class_name, :versioned_foreign_key, :versioned_table_name, :versioned_inheritance_column, cattr_accessor :versioned_class_name, :versioned_foreign_key, :versioned_table_name, :versioned_inheritance_column,
:version_column, :max_version_limit, :track_changed_attributes, :version_condition, :version_sequence_name, :non_versioned_columns, :version_column, :max_version_limit, :track_altered_attributes, :version_condition, :version_sequence_name, :non_versioned_columns,
:version_association_options :version_association_options
# legacy # legacy
@@ -171,7 +186,7 @@ module ActiveRecord #:nodoc:
alias_method :non_versioned_fields=, :non_versioned_columns= alias_method :non_versioned_fields=, :non_versioned_columns=
end end
send :attr_accessor, :changed_attributes send :attr_accessor, :altered_attributes
self.versioned_class_name = options[:class_name] || "Version" self.versioned_class_name = options[:class_name] || "Version"
self.versioned_foreign_key = options[:foreign_key] || self.to_s.foreign_key self.versioned_foreign_key = options[:foreign_key] || self.to_s.foreign_key
@@ -184,8 +199,7 @@ module ActiveRecord #:nodoc:
self.non_versioned_columns = [self.primary_key, inheritance_column, 'version', 'lock_version', versioned_inheritance_column] self.non_versioned_columns = [self.primary_key, inheritance_column, 'version', 'lock_version', versioned_inheritance_column]
self.version_association_options = { self.version_association_options = {
:class_name => "#{self.to_s}::#{versioned_class_name}", :class_name => "#{self.to_s}::#{versioned_class_name}",
:foreign_key => "#{versioned_foreign_key}", :foreign_key => versioned_foreign_key,
:order => 'version',
:dependent => :delete_all :dependent => :delete_all
}.merge(options[:association_options] || {}) }.merge(options[:association_options] || {})
@@ -199,15 +213,25 @@ module ActiveRecord #:nodoc:
end end
class_eval do class_eval do
has_many :versions, version_association_options has_many :versions, version_association_options do
# finds earliest version of this record
def earliest
@earliest ||= find(:first, :order => 'version')
end
# find latest version of this record
def latest
@latest ||= find(:first, :order => 'version desc')
end
end
before_save :set_new_version before_save :set_new_version
after_create :save_version_on_create after_create :save_version_on_create
after_update :save_version after_update :save_version
after_save :clear_old_versions after_save :clear_old_versions
after_save :clear_changed_attributes after_save :clear_altered_attributes
unless options[:if_changed].nil? unless options[:if_changed].nil?
self.track_changed_attributes = true self.track_altered_attributes = true
options[:if_changed] = [options[:if_changed]] unless options[:if_changed].is_a?(Array) options[:if_changed] = [options[:if_changed]] unless options[:if_changed].is_a?(Array)
options[:if_changed].each do |attr_name| options[:if_changed].each do |attr_name|
define_method("#{attr_name}=") do |value| define_method("#{attr_name}=") do |value|
@@ -222,8 +246,33 @@ module ActiveRecord #:nodoc:
# create the dynamic versioned model # create the dynamic versioned model
const_set(versioned_class_name, Class.new(ActiveRecord::Base)).class_eval do const_set(versioned_class_name, Class.new(ActiveRecord::Base)).class_eval do
def self.reloadable? ; false ; end def self.reloadable? ; false ; end
# find first version before the given version
def self.before(version)
find :first, :order => 'version desc',
:conditions => ["#{original_class.versioned_foreign_key} = ? and version < ?", version.send(original_class.versioned_foreign_key), version.version]
end
# find first version after the given version.
def self.after(version)
find :first, :order => 'version',
:conditions => ["#{original_class.versioned_foreign_key} = ? and version > ?", version.send(original_class.versioned_foreign_key), version.version]
end
def previous
self.class.before(self)
end
def next
self.class.after(self)
end
def versions_count
page.version
end
end end
versioned_class.cattr_accessor :original_class
versioned_class.original_class = self
versioned_class.set_table_name versioned_table_name versioned_class.set_table_name versioned_table_name
versioned_class.belongs_to self.to_s.demodulize.underscore.to_sym, versioned_class.belongs_to self.to_s.demodulize.underscore.to_sym,
:class_name => "::#{self.to_s}", :class_name => "::#{self.to_s}",
@@ -238,6 +287,11 @@ module ActiveRecord #:nodoc:
base.extend ClassMethods base.extend ClassMethods
end end
# Finds a specific version of this record
def find_version(version = nil)
self.class.find_version(id, version)
end
# Saves a version of the model if applicable # Saves a version of the model if applicable
def save_version def save_version
save_version_on_create if save_version? save_version_on_create if save_version?
@@ -263,16 +317,8 @@ module ActiveRecord #:nodoc:
end end
end end
# Finds a specific version of this model. def versions_count
def find_version(version) version
return version if version.is_a?(self.class.versioned_class)
return nil if version.is_a?(ActiveRecord::Base)
find_versions(:conditions => ['version = ?', version], :limit => 1).first
end
# Finds versions of this model. Takes an options hash like <tt>find</tt>
def find_versions(options = {})
versions.find(:all, options)
end end
# Reverts a model to a given version. Takes either a version number or an instance of the versioned model # Reverts a model to a given version. Takes either a version number or an instance of the versioned model
@@ -280,7 +326,7 @@ module ActiveRecord #:nodoc:
if version.is_a?(self.class.versioned_class) if version.is_a?(self.class.versioned_class)
return false unless version.send(self.class.versioned_foreign_key) == self.id and !version.new_record? return false unless version.send(self.class.versioned_foreign_key) == self.id and !version.new_record?
else else
return false unless version = find_version(version) return false unless version = versions.find_by_version(version)
end end
self.clone_versioned_model(version, self) self.clone_versioned_model(version, self)
self.send("#{self.class.version_column}=", version.version) self.send("#{self.class.version_column}=", version.version)
@@ -318,8 +364,8 @@ module ActiveRecord #:nodoc:
# If called with a single parameter, gets whether the parameter has changed. # If called with a single parameter, gets whether the parameter has changed.
def changed?(attr_name = nil) def changed?(attr_name = nil)
attr_name.nil? ? attr_name.nil? ?
(!self.class.track_changed_attributes || (changed_attributes && changed_attributes.length > 0)) : (!self.class.track_altered_attributes || (altered_attributes && altered_attributes.length > 0)) :
(changed_attributes && changed_attributes.include?(attr_name.to_s)) (altered_attributes && altered_attributes.include?(attr_name.to_s))
end end
# keep old dirty? method # keep old dirty? method
@@ -328,7 +374,7 @@ module ActiveRecord #:nodoc:
# Clones a model. Used when saving a new version or reverting a model's version. # Clones a model. Used when saving a new version or reverting a model's version.
def clone_versioned_model(orig_model, new_model) def clone_versioned_model(orig_model, new_model)
self.versioned_attributes.each do |key| self.versioned_attributes.each do |key|
new_model.send("#{key}=", orig_model.attributes[key]) if orig_model.has_attribute?(key) new_model.send("#{key}=", orig_model.send(key)) if orig_model.has_attribute?(key)
end end
if orig_model.is_a?(self.class.versioned_class) if orig_model.is_a?(self.class.versioned_class)
@@ -391,28 +437,30 @@ module ActiveRecord #:nodoc:
end end
# clears current changed attributes. Called after save. # clears current changed attributes. Called after save.
def clear_changed_attributes def clear_altered_attributes
self.changed_attributes = [] self.altered_attributes = []
end end
def write_changed_attribute(attr_name, attr_value) def write_changed_attribute(attr_name, attr_value)
# Convert to db type for comparison. Avoids failing Float<=>String comparisons. # Convert to db type for comparison. Avoids failing Float<=>String comparisons.
attr_value_for_db = self.class.columns_hash[attr_name.to_s].type_cast(attr_value) attr_value_for_db = self.class.columns_hash[attr_name.to_s].type_cast(attr_value)
(self.changed_attributes ||= []) << attr_name.to_s unless self.changed?(attr_name) || self.send(attr_name) == attr_value_for_db (self.altered_attributes ||= []) << attr_name.to_s unless self.changed?(attr_name) || self.send(attr_name) == attr_value_for_db
write_attribute(attr_name, attr_value_for_db) write_attribute(attr_name, attr_value_for_db)
end end
private
CALLBACKS.each do |attr_name|
alias_method "orig_#{attr_name}".to_sym, attr_name
end
module ClassMethods module ClassMethods
# Finds a specific version of a specific row of this model # Finds a specific version of a specific row of this model
def find_version(id, version) def find_version(id, version = nil)
find_versions(id, return find(id) unless version
:conditions => ["#{versioned_foreign_key} = ? AND version = ?", id, version],
:limit => 1).first conditions = ["#{versioned_foreign_key} = ? AND version = ?", id, version]
options = { :conditions => conditions, :limit => 1 }
if result = find_versions(id, options).first
result
else
raise RecordNotFound, "Couldn't find #{name} with ID=#{id} and VERSION=#{version}"
end
end end
# Finds versions of a specific model. Takes an options hash like <tt>find</tt> # Finds versions of a specific model. Takes an options hash like <tt>find</tt>
@@ -449,13 +497,17 @@ module ActiveRecord #:nodoc:
updated_col = col if !updated_col && %(updated_at updated_on).include?(col.name) updated_col = col if !updated_col && %(updated_at updated_on).include?(col.name)
self.connection.add_column versioned_table_name, col.name, col.type, self.connection.add_column versioned_table_name, col.name, col.type,
:limit => col.limit, :limit => col.limit,
:default => col.default :default => col.default,
:scale => col.scale,
:precision => col.precision
end end
if type_col = self.columns_hash[inheritance_column] if type_col = self.columns_hash[inheritance_column]
self.connection.add_column versioned_table_name, versioned_inheritance_column, type_col.type, self.connection.add_column versioned_table_name, versioned_inheritance_column, type_col.type,
:limit => type_col.limit, :limit => type_col.limit,
:default => type_col.default :default => type_col.default,
:scale => type_col.scale,
:precision => type_col.precision
end end
if updated_col.nil? if updated_col.nil?
@@ -477,16 +529,17 @@ module ActiveRecord #:nodoc:
def without_revision(&block) def without_revision(&block)
class_eval do class_eval do
CALLBACKS.each do |attr_name| CALLBACKS.each do |attr_name|
alias_method "orig_#{attr_name}".to_sym, attr_name
alias_method attr_name, :empty_callback alias_method attr_name, :empty_callback
end end
end end
result = block.call block.call
ensure
class_eval do class_eval do
CALLBACKS.each do |attr_name| CALLBACKS.each do |attr_name|
alias_method attr_name, "orig_#{attr_name}".to_sym alias_method attr_name, "orig_#{attr_name}".to_sym
end end
end end
result
end end
# Turns off optimistic locking for the duration of the block # Turns off optimistic locking for the duration of the block
@@ -1,12 +1,21 @@
$:.unshift(File.dirname(__FILE__) + '/../../../rails/activesupport/lib')
$:.unshift(File.dirname(__FILE__) + '/../../../rails/activerecord/lib')
$:.unshift(File.dirname(__FILE__) + '/../lib') $:.unshift(File.dirname(__FILE__) + '/../lib')
require 'test/unit' require 'test/unit'
require File.expand_path(File.join(File.dirname(__FILE__), '../../../../config/environment.rb')) begin
require 'active_record/fixtures' require 'active_support'
require 'active_record'
require 'active_record/fixtures'
rescue LoadError
require 'rubygems'
retry
end
require 'acts_as_versioned'
config = YAML::load(IO.read(File.dirname(__FILE__) + '/database.yml')) config = YAML::load(IO.read(File.dirname(__FILE__) + '/database.yml'))
ActiveRecord::Base.logger = Logger.new(File.dirname(__FILE__) + "/debug.log") ActiveRecord::Base.logger = Logger.new(File.dirname(__FILE__) + "/debug.log")
ActiveRecord::Base.establish_connection(config[ENV['DB'] || 'sqlite']) ActiveRecord::Base.configurations = {'test' => config[ENV['DB'] || 'sqlite3']}
ActiveRecord::Base.establish_connection(ActiveRecord::Base.configurations['test'])
load(File.dirname(__FILE__) + "/schema.rb") load(File.dirname(__FILE__) + "/schema.rb")
@@ -19,17 +28,9 @@ if ENV['DB'] == 'postgresql'
end end
Test::Unit::TestCase.fixture_path = File.dirname(__FILE__) + "/fixtures/" Test::Unit::TestCase.fixture_path = File.dirname(__FILE__) + "/fixtures/"
$LOAD_PATH.unshift(Test::Unit::TestCase.fixture_path) $:.unshift(Test::Unit::TestCase.fixture_path)
class Test::Unit::TestCase #:nodoc: class Test::Unit::TestCase #:nodoc:
def create_fixtures(*table_names)
if block_given?
Fixtures.create_fixtures(Test::Unit::TestCase.fixture_path, table_names) { yield }
else
Fixtures.create_fixtures(Test::Unit::TestCase.fixture_path, table_names)
end
end
# Turn off transactional fixtures if you're working with MyISAM tables in MySQL # Turn off transactional fixtures if you're working with MyISAM tables in MySQL
self.use_transactional_fixtures = true self.use_transactional_fixtures = true
@@ -1,6 +1,6 @@
class Widget < ActiveRecord::Base class Widget < ActiveRecord::Base
acts_as_versioned :sequence_name => 'widgets_seq', :association_options => { acts_as_versioned :sequence_name => 'widgets_seq', :association_options => {
:dependent => nil, :order => 'version desc' :dependent => :nullify, :order => 'version desc'
} }
non_versioned_columns << 'foo' non_versioned_columns << 'foo'
end end
@@ -9,8 +9,13 @@ if ActiveRecord::Base.connection.supports_migrations?
class MigrationTest < Test::Unit::TestCase class MigrationTest < Test::Unit::TestCase
self.use_transactional_fixtures = false self.use_transactional_fixtures = false
def teardown def teardown
ActiveRecord::Base.connection.initialize_schema_information if ActiveRecord::Base.connection.respond_to?(:initialize_schema_information)
ActiveRecord::Base.connection.update "UPDATE schema_info SET version = 0" ActiveRecord::Base.connection.initialize_schema_information
ActiveRecord::Base.connection.update "UPDATE schema_info SET version = 0"
else
ActiveRecord::Base.connection.initialize_schema_migrations_table
ActiveRecord::Base.connection.assume_migrated_upto_version(0)
end
Thing.connection.drop_table "things" rescue nil Thing.connection.drop_table "things" rescue nil
Thing.connection.drop_table "thing_versions" rescue nil Thing.connection.drop_table "thing_versions" rescue nil
@@ -21,9 +26,18 @@ if ActiveRecord::Base.connection.supports_migrations?
assert_raises(ActiveRecord::StatementInvalid) { Thing.create :title => 'blah blah' } assert_raises(ActiveRecord::StatementInvalid) { Thing.create :title => 'blah blah' }
# take 'er up # take 'er up
ActiveRecord::Migrator.up(File.dirname(__FILE__) + '/fixtures/migrations/') ActiveRecord::Migrator.up(File.dirname(__FILE__) + '/fixtures/migrations/')
t = Thing.create :title => 'blah blah' t = Thing.create :title => 'blah blah', :price => 123.45, :type => 'Thing'
assert_equal 1, t.versions.size assert_equal 1, t.versions.size
# check that the price column has remembered its value correctly
assert_equal t.price, t.versions.first.price
assert_equal t.title, t.versions.first.title
assert_equal t[:type], t.versions.first[:type]
# make sure that the precision of the price column has been preserved
assert_equal 7, Thing::Version.columns.find{|c| c.name == "price"}.precision
assert_equal 2, Thing::Version.columns.find{|c| c.name == "price"}.scale
# now lets take 'er back down # now lets take 'er back down
ActiveRecord::Migrator.down(File.dirname(__FILE__) + '/fixtures/migrations/') ActiveRecord::Migrator.down(File.dirname(__FILE__) + '/fixtures/migrations/')
assert_raises(ActiveRecord::StatementInvalid) { Thing.create :title => 'blah blah' } assert_raises(ActiveRecord::StatementInvalid) { Thing.create :title => 'blah blah' }
@@ -4,9 +4,10 @@ require File.join(File.dirname(__FILE__), 'fixtures/widget')
class VersionedTest < Test::Unit::TestCase class VersionedTest < Test::Unit::TestCase
fixtures :pages, :page_versions, :locked_pages, :locked_pages_revisions, :authors, :landmarks, :landmark_versions fixtures :pages, :page_versions, :locked_pages, :locked_pages_revisions, :authors, :landmarks, :landmark_versions
set_fixture_class :page_versions => Page::Version
def test_saves_versioned_copy def test_saves_versioned_copy
p = Page.create :title => 'first title', :body => 'first body' p = Page.create! :title => 'first title', :body => 'first body'
assert !p.new_record? assert !p.new_record?
assert_equal 1, p.versions.size assert_equal 1, p.versions.size
assert_equal 1, p.version assert_equal 1, p.version
@@ -69,7 +70,7 @@ class VersionedTest < Test::Unit::TestCase
end end
def test_saves_versioned_copy_with_options def test_saves_versioned_copy_with_options
p = LockedPage.create :title => 'first title' p = LockedPage.create! :title => 'first title'
assert !p.new_record? assert !p.new_record?
assert_equal 1, p.versions.size assert_equal 1, p.versions.size
assert_instance_of LockedPage.versioned_class, p.versions.first assert_instance_of LockedPage.versioned_class, p.versions.first
@@ -96,7 +97,7 @@ class VersionedTest < Test::Unit::TestCase
end end
def test_saves_versioned_copy_with_sti def test_saves_versioned_copy_with_sti
p = SpecialLockedPage.create :title => 'first title' p = SpecialLockedPage.create! :title => 'first title'
assert !p.new_record? assert !p.new_record?
assert_equal 1, p.versions.size assert_equal 1, p.versions.size
assert_instance_of LockedPage.versioned_class, p.versions.first assert_instance_of LockedPage.versioned_class, p.versions.first
@@ -127,7 +128,7 @@ class VersionedTest < Test::Unit::TestCase
end end
def test_version_if_condition def test_version_if_condition
p = Page.create :title => "title" p = Page.create! :title => "title"
assert_equal 1, p.version assert_equal 1, p.version
Page.feeling_good = false Page.feeling_good = false
@@ -144,7 +145,7 @@ class VersionedTest < Test::Unit::TestCase
alias_method :feeling_good?, :new_feeling_good alias_method :feeling_good?, :new_feeling_good
end end
p = Page.create :title => "title" p = Page.create! :title => "title"
assert_equal 1, p.version # version does not increment assert_equal 1, p.version # version does not increment
assert_equal 1, p.versions(true).size assert_equal 1, p.versions(true).size
@@ -165,7 +166,7 @@ class VersionedTest < Test::Unit::TestCase
old_condition = Page.version_condition old_condition = Page.version_condition
Page.version_condition = Proc.new { |page| page.title[0..0] == 'b' } Page.version_condition = Proc.new { |page| page.title[0..0] == 'b' }
p = Page.create :title => "title" p = Page.create! :title => "title"
assert_equal 1, p.version # version does not increment assert_equal 1, p.version # version does not increment
assert_equal 1, p.versions(true).size assert_equal 1, p.versions(true).size
@@ -182,7 +183,7 @@ class VersionedTest < Test::Unit::TestCase
end end
def test_version_no_limit def test_version_no_limit
p = Page.create :title => "title", :body => 'first body' p = Page.create! :title => "title", :body => 'first body'
p.save p.save
p.save p.save
5.times do |i| 5.times do |i|
@@ -191,7 +192,7 @@ class VersionedTest < Test::Unit::TestCase
end end
def test_version_max_limit def test_version_max_limit
p = LockedPage.create :title => "title" p = LockedPage.create! :title => "title"
p.update_attributes(:title => "title1") p.update_attributes(:title => "title1")
p.update_attributes(:title => "title2") p.update_attributes(:title => "title2")
5.times do |i| 5.times do |i|
@@ -200,21 +201,19 @@ class VersionedTest < Test::Unit::TestCase
end end
end end
def test_track_changed_attributes_default_value def test_track_altered_attributes_default_value
assert !Page.track_changed_attributes assert !Page.track_altered_attributes
assert LockedPage.track_changed_attributes assert LockedPage.track_altered_attributes
assert SpecialLockedPage.track_changed_attributes assert SpecialLockedPage.track_altered_attributes
end end
def test_version_order def test_version_order
assert_equal 23, pages(:welcome).versions.first.version assert_equal 23, pages(:welcome).versions.first.version
assert_equal 24, pages(:welcome).versions.last.version assert_equal 24, pages(:welcome).versions.last.version
assert_equal 23, pages(:welcome).find_versions.first.version
assert_equal 24, pages(:welcome).find_versions.last.version
end end
def test_track_changed_attributes def test_track_altered_attributes
p = LockedPage.create :title => "title" p = LockedPage.create! :title => "title"
assert_equal 1, p.lock_version assert_equal 1, p.lock_version
assert_equal 1, p.versions(true).size assert_equal 1, p.versions(true).size
@@ -246,17 +245,28 @@ class VersionedTest < Test::Unit::TestCase
def test_find_versions def test_find_versions
assert_equal 2, locked_pages(:welcome).versions.size assert_equal 2, locked_pages(:welcome).versions.size
assert_equal 1, locked_pages(:welcome).find_versions(:conditions => ['title LIKE ?', '%weblog%']).length assert_equal 1, locked_pages(:welcome).versions.find(:all, :conditions => ['title LIKE ?', '%weblog%']).length
assert_equal 2, locked_pages(:welcome).find_versions(:conditions => ['title LIKE ?', '%web%']).length assert_equal 2, locked_pages(:welcome).versions.find(:all, :conditions => ['title LIKE ?', '%web%']).length
assert_equal 0, locked_pages(:thinking).find_versions(:conditions => ['title LIKE ?', '%web%']).length assert_equal 0, locked_pages(:thinking).versions.find(:all, :conditions => ['title LIKE ?', '%web%']).length
assert_equal 2, locked_pages(:welcome).find_versions.length assert_equal 2, locked_pages(:welcome).versions.length
end
def test_find_version
assert_equal page_versions(:welcome_1), Page.find_version(pages(:welcome).id, 23)
assert_equal page_versions(:welcome_2), Page.find_version(pages(:welcome).id, 24)
assert_equal pages(:welcome), Page.find_version(pages(:welcome).id)
assert_equal page_versions(:welcome_1), pages(:welcome).find_version(23)
assert_equal page_versions(:welcome_2), pages(:welcome).find_version(24)
assert_equal pages(:welcome), pages(:welcome).find_version
assert_raise(ActiveRecord::RecordNotFound) { Page.find_version(pages(:welcome).id, 1) }
assert_raise(ActiveRecord::RecordNotFound) { Page.find_version(0, 23) }
end end
def test_with_sequence def test_with_sequence
assert_equal 'widgets_seq', Widget.versioned_class.sequence_name assert_equal 'widgets_seq', Widget.versioned_class.sequence_name
Widget.create :name => 'new widget' 3.times { Widget.create! :name => 'new widget' }
Widget.create :name => 'new widget'
Widget.create :name => 'new widget'
assert_equal 3, Widget.count assert_equal 3, Widget.count
assert_equal 3, Widget.versioned_class.count assert_equal 3, Widget.versioned_class.count
end end
@@ -283,11 +293,11 @@ class VersionedTest < Test::Unit::TestCase
association = Widget.reflect_on_association(:versions) association = Widget.reflect_on_association(:versions)
options = association.options options = association.options
assert_nil options[:dependent] assert_equal :nullify, options[:dependent]
assert_equal 'version desc', options[:order] assert_equal 'version desc', options[:order]
assert_equal 'widget_id', options[:foreign_key] assert_equal 'widget_id', options[:foreign_key]
widget = Widget.create :name => 'new widget' widget = Widget.create! :name => 'new widget'
assert_equal 1, Widget.count assert_equal 1, Widget.count
assert_equal 1, Widget.versioned_class.count assert_equal 1, Widget.versioned_class.count
widget.destroy widget.destroy
@@ -301,13 +311,37 @@ class VersionedTest < Test::Unit::TestCase
assert_equal page, page_version.page assert_equal page, page_version.page
end end
def test_unchanged_attributes def test_unaltered_attributes
landmarks(:washington).attributes = landmarks(:washington).attributes landmarks(:washington).attributes = landmarks(:washington).attributes.except("id")
assert !landmarks(:washington).changed? assert !landmarks(:washington).changed?
end end
def test_unchanged_string_attributes def test_unchanged_string_attributes
landmarks(:washington).attributes = landmarks(:washington).attributes.inject({}) { |params, (key, value)| params.update key => value.to_s } landmarks(:washington).attributes = landmarks(:washington).attributes.except("id").inject({}) { |params, (key, value)| params.update(key => value.to_s) }
assert !landmarks(:washington).changed? assert !landmarks(:washington).changed?
end end
def test_should_find_earliest_version
assert_equal page_versions(:welcome_1), pages(:welcome).versions.earliest
end
def test_should_find_latest_version
assert_equal page_versions(:welcome_2), pages(:welcome).versions.latest
end
def test_should_find_previous_version
assert_equal page_versions(:welcome_1), page_versions(:welcome_2).previous
assert_equal page_versions(:welcome_1), pages(:welcome).versions.before(page_versions(:welcome_2))
end
def test_should_find_next_version
assert_equal page_versions(:welcome_2), page_versions(:welcome_1).next
assert_equal page_versions(:welcome_2), pages(:welcome).versions.after(page_versions(:welcome_1))
end
def test_should_find_version_count
assert_equal 24, pages(:welcome).versions_count
assert_equal 24, page_versions(:welcome_1).versions_count
assert_equal 24, page_versions(:welcome_2).versions_count
end
end end