Class: VestalVersions::Version

Inherits:
ActiveRecord::Base
  • Object
show all
Includes:
Comparable
Defined in:
lib/vestal_versions/version.rb

Overview

The ActiveRecord model representing versions.

Instance Method Summary collapse

Instance Method Details

#<=>(other) ⇒ Object

In conjunction with the included Comparable module, allows comparison of version records based on their corresponding version numbers, creation timestamps and IDs.



21
22
23
# File 'lib/vestal_versions/version.rb', line 21

def <=>(other)
  [number, created_at, id].map(&:to_i) <=> [other.number, other.created_at, other.id].map(&:to_i)
end

#changesObject



14
15
16
# File 'lib/vestal_versions/version.rb', line 14

def changes
  self[:modifications]
end

#initial?Boolean

Returns whether the version has a version number of 1. Useful when deciding whether to ignore the version during reversion, as initial versions have no serialized changes attached. Helps maintain backwards compatibility.

Returns:

  • (Boolean)


28
29
30
# File 'lib/vestal_versions/version.rb', line 28

def initial?
  number == 1
end

#original_numberObject

Returns the original version number that this version was.



33
34
35
36
37
38
39
40
# File 'lib/vestal_versions/version.rb', line 33

def original_number
  if reverted_from.nil?
    number
  else
    version = versioned.versions.at(reverted_from)
    version.nil? ? 1 : version.original_number
  end
end

#restoreObject



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/vestal_versions/version.rb', line 53

def restore
  if tag == 'deleted'
    attrs = modifications

    class_name = attrs['type'].blank? ? versioned_type : attrs['type']
    klass = class_name.constantize
    model = klass.new

    attrs.each do |k, v|
      begin
        model.send "#{k}=", v
      rescue NoMethodError
        logger.warn "Attribute #{k} does not exist on #{class_name} (Version id: #{id})." rescue nil
      end
    end

    model
  else
    latest_version = self.class.find(:first, :conditions => {:versioned_id => versioned_id, :versioned_type => versioned_type, :tag => 'deleted'})
    latest_version.nil? ? nil : latest_version.restore
  end
end

#restore!Object



42
43
44
45
46
47
48
49
50
51
# File 'lib/vestal_versions/version.rb', line 42

def restore!
  model = restore
  
  if model
    model.save!
    destroy
  end
  
  model
end