Refactor Version to use some named scopes.
This commit is contained in:
parent
26424b748a
commit
9fc312c129
|
@ -2,6 +2,20 @@ class Version < ActiveRecord::Base
|
|||
belongs_to :item, :polymorphic => true
|
||||
validates_presence_of :event
|
||||
|
||||
named_scope :with_item_keys, lambda { |item_type, item_id| {
|
||||
:conditions => { :item_type => item_type, :item_id => item_id }
|
||||
} }
|
||||
|
||||
named_scope :subsequent, lambda { |version| {
|
||||
:conditions => ["id > ?", version.is_a?(ActiveRecord::Base) ? version.id : version],
|
||||
:order => "id ASC",
|
||||
} }
|
||||
|
||||
named_scope :preceding, lambda { |version| {
|
||||
:conditions => ["id < ?", version.is_a?(ActiveRecord::Base) ? version.id : version],
|
||||
:order => "id DESC",
|
||||
} }
|
||||
|
||||
# Restore the item from this version.
|
||||
#
|
||||
# This will automatically restore all :has_one associations as they were "at the time",
|
||||
|
@ -69,19 +83,20 @@ class Version < ActiveRecord::Base
|
|||
whodunnit
|
||||
end
|
||||
|
||||
def sibling_versions
|
||||
Version.with_item_keys(item_type, item_id)
|
||||
end
|
||||
|
||||
def next
|
||||
Version.first :conditions => ["id > ? AND item_type = ? AND item_id = ?", id, item_type, item_id],
|
||||
:order => 'id ASC'
|
||||
sibling_versions.subsequent(self).first
|
||||
end
|
||||
|
||||
def previous
|
||||
Version.first :conditions => ["id < ? AND item_type = ? AND item_id = ?", id, item_type, item_id],
|
||||
:order => 'id DESC'
|
||||
sibling_versions.preceding(self).first
|
||||
end
|
||||
|
||||
def index
|
||||
Version.all(:conditions => ["item_type = ? AND item_id = ?", item_type, item_id],
|
||||
:order => 'id ASC').index(self)
|
||||
sibling_versions.all(:select => :id, :order => "id ASC").map(&:id).index(self.id)
|
||||
end
|
||||
|
||||
private
|
||||
|
|
Loading…
Reference in New Issue