lib/vestal_versions.rb in laserlemon-vestal_versions-0.6.0 vs lib/vestal_versions.rb in laserlemon-vestal_versions-0.7.0
- old
+ new
@@ -7,17 +7,17 @@
end
module ClassMethods
def versioned
has_many :versions, :as => :versioned, :order => 'versions.number ASC', :dependent => :delete_all do
- def between(from_value, to_value)
- from, to = number_at(from_value), number_at(to_value)
- return [] if from.nil? || to.nil?
- condition = (from == to) ? to : Range.new(*[from, to].sort)
+ def between(from, to)
+ from_number, to_number = number_at(from), number_at(to)
+ return [] if from_number.nil? || to_number.nil?
+ condition = (from_number == to_number) ? to_number : Range.new(*[from_number, to_number].sort)
all(
:conditions => {:number => condition},
- :order => "versions.number #{(from > to) ? 'DESC' : 'ASC'}"
+ :order => "versions.number #{(from_number > to_number) ? 'DESC' : 'ASC'}"
)
end
def at(value)
case value
@@ -86,29 +86,40 @@
def reload_with_versions(*args)
reset_version
reload_without_versions(*args)
end
- def revert_to(value)
- to_value = versions.number_at(value)
- return version if to_value == version
- chain = versions.between(version, to_value)
- return version if chain.empty?
+ def changes_between(from, to)
+ from_number, to_number = versions.number_at(from), versions.number_at(to)
+ return {} if from_number == to_number
+ chain = versions.between(from_number, to_number)
+ return {} if chain.empty?
- new_version = chain.last.number
backward = chain.first > chain.last
backward ? chain.pop : chain.shift
timestamps = %w(created_at created_on updated_at updated_on)
- chain.each do |version|
+ chain.inject({}) do |changes, version|
version.changes.except(*timestamps).each do |attribute, change|
- new_value = backward ? change.first : change.last
- write_attribute(attribute, new_value)
+ change.reverse! if backward
+ new_change = [changes.fetch(attribute, change).first, change.last]
+ changes.update(attribute => new_change)
end
+ changes
end
+ end
- reset_version(new_version)
+ def revert_to(value)
+ to_number = versions.number_at(value)
+ changes = changes_between(version, to_number)
+ return version if changes.empty?
+
+ changes.each do |attribute, change|
+ write_attribute(attribute, change.last)
+ end
+
+ reset_version(to_number)
end
def revert_to!(value)
revert_to(value)
reset_version if saved = save