lib/vestal_versions.rb in laserlemon-vestal_versions-0.4.3 vs lib/vestal_versions.rb in laserlemon-vestal_versions-0.4.4
- old
+ new
@@ -7,37 +7,36 @@
end
module ClassMethods
def versioned
has_many :versions, :as => :versioned, :order => 'versions.number ASC', :dependent => :destroy 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)
+ all(
+ :conditions => {:number => condition},
+ :order => "versions.number #{(from > to) ? 'DESC' : 'ASC'}"
+ )
+ end
+
def at(value)
case value
when Version then value
when Numeric then find_by_number(value.floor)
when Symbol then respond_to?(value) ? send(value) : nil
when Date, Time then last(:conditions => ['versions.created_at <= ?', value.to_time])
end
end
- def between(from_value, to_value)
- from, to = number_at(from_value), number_at(to_value)
- return [] if from.nil? || to.nil? || (from == to)
- all(
- :conditions => {:number => Range.new(*[from, to].sort)},
- :order => "versions.number #{(from > to) ? 'DESC' : 'ASC'}"
- )
- end
-
- private
-
- def number_at(value)
- case value
- when Version then value.number
- when Numeric then value.floor
- when Symbol, Date, Time then at(value).try(:number)
- end
+ def number_at(value)
+ case value
+ when Version then value.number
+ when Numeric then value.floor
+ when Symbol, Date, Time then at(value).try(:number)
end
+ end
end
after_save :create_version, :if => :needs_version?
include InstanceMethods
@@ -45,11 +44,10 @@
end
end
module InstanceMethods
private
-
def needs_version?
!changed.empty?
end
def reset_version(new_version = nil)
@@ -67,11 +65,10 @@
reset_version
end
public
-
def version
@version ||= last_version
end
def last_version
@@ -79,19 +76,21 @@
end
def reverted?
version != last_version
end
-
+
def reload_with_versions(*args)
reset_version
reload_without_versions(*args)
end
def revert_to(value)
- chain = versions.between(version, value)
- return version unless chain.size > 1
+ to_value = versions.number_at(value)
+ return version if to_value == version
+ chain = versions.between(version, to_value)
+ return version if chain.empty?
new_version = chain.last.number
backward = chain.first > chain.last
backward ? chain.pop : chain.shift
@@ -112,10 +111,10 @@
reset_version if saved = save
saved
end
def last_changes
- return {} if version == 1
+ return {} if version.nil? || version == 1
versions.at(version).changes
end
def last_changed
last_changes.keys