Module: Mongoid::Delorean::Trackable

Defined in:
lib/mongoid/delorean/trackable.rb

Defined Under Namespace

Modules: CommonEmbeddedMethods, CommonInstanceMethods

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(klass) ⇒ Object



5
6
7
8
9
10
# File 'lib/mongoid/delorean/trackable.rb', line 5

def self.included(klass)
  super
  klass.field :version, type: Integer, default: 0
  klass.before_save :save_version
  klass.send(:include, Mongoid::Delorean::Trackable::CommonInstanceMethods)
end

Instance Method Details

#revert!(version = (self.version - 1)) ⇒ Object



44
45
46
47
48
49
50
51
52
# File 'lib/mongoid/delorean/trackable.rb', line 44

def revert!(version = (self.version - 1))
  old_version = self.versions.where(version: version).first
  if old_version
    old_version.full_attributes.each do |key, value|
      self.write_attribute(key, value)
    end
    self.save!
  end
end

#save_versionObject



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/mongoid/delorean/trackable.rb', line 16

def save_version
  if self.track_history?
    last_version = self.versions.last
    _version = last_version ? last_version.version + 1 : 1

    _attributes = self.attributes_with_relations
    _attributes.merge!("version" => _version)
    _changes = self.changes_with_relations.dup
    _changes.merge!("version" => [self.version_was, _version])

    Mongoid::Delorean::History.create(original_class: self.class.name, original_class_id: self.id, version: _version, altered_attributes: _changes, full_attributes: _attributes).inspect
    self.without_history_tracking do
      self.version = _version
      self.save!
    end
  end
end

#track_history?Boolean

Returns:

  • (Boolean)


34
35
36
# File 'lib/mongoid/delorean/trackable.rb', line 34

def track_history?
  @__track_changes.nil? ? Mongoid::Delorean.config.track_history : @__track_changes
end

#versionsObject



12
13
14
# File 'lib/mongoid/delorean/trackable.rb', line 12

def versions
  Mongoid::Delorean::History.where(original_class: self.class.name, original_class_id: self.id)
end

#without_history_trackingObject



38
39
40
41
42
# File 'lib/mongoid/delorean/trackable.rb', line 38

def without_history_tracking
  @__track_changes = false
  yield
  @__track_changes = Mongoid::Delorean.config.track_history
end