Module: Immutability::WithMemory

Includes:
Immutability
Defined in:
lib/immutability/with_memory.rb

Overview

Extends Immutability to remember version and previous state of instance.

Author:

Defined Under Namespace

Modules: ClassMethods

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Immutability

with_memory

Instance Attribute Details

#parentObject (readonly)

Returns the previous version (immutable instance).

Returns:

  • (Object)

    the previous version (immutable instance)



50
51
52
# File 'lib/immutability/with_memory.rb', line 50

def parent
  @parent
end

#versionInteger (readonly)

Returns the current version number of the instance.

Returns:

  • (Integer)

    the current version number of the instance



44
45
46
# File 'lib/immutability/with_memory.rb', line 44

def version
  @version
end

Class Method Details

.included(klass) ⇒ Object



89
90
91
# File 'lib/immutability/with_memory.rb', line 89

def self.included(klass)
  klass.instance_eval { extend ClassMethods }
end

Instance Method Details

#at(point) ⇒ Object?

Returns an ancestor of the instance at some point in the past

Parameters:

  • point (#to_i)

    Either a positive number of version, or a negative number of versions (snapshots) before now. 0 stands for the first version.

Returns:



84
85
86
# File 'lib/immutability/with_memory.rb', line 84

def at(point)
  Object.new(self).at(point)
end

#forget_historyObject

Forgets the previous history of the object

Returns a new instance with the same variables, except for [#version] and [#parent] that are set to 0 and nil.

Returns:



72
73
74
# File 'lib/immutability/with_memory.rb', line 72

def forget_history
  update { @version, @parent = 0 }
end

#update(&block) ⇒ Object

Redefines the update so that it increment version and refer to the previous snapshot of the continuous object

Parameters:

  • block (Proc)


57
58
59
60
61
62
63
# File 'lib/immutability/with_memory.rb', line 57

def update(&block)
  current = [version + 1, self]
  super do
    @version, @parent = current
    instance_eval(&block) if block
  end
end