Class: Redis::TrackedHash

Inherits:
Hash
  • Object
show all
Defined in:
lib/redis/tracked_hash.rb

Direct Known Subclasses

NativeHash

Instance Method Summary collapse

Methods inherited from Hash

#stringify_keys!

Instance Method Details

#addedObject



31
32
33
# File 'lib/redis/tracked_hash.rb', line 31

def added
  self.keys - original.keys
end

#changedObject



21
22
23
24
25
# File 'lib/redis/tracked_hash.rb', line 21

def changed
  changes = keys.select do |key|
    self[key] != original[key]
  end
end

#deletedObject



27
28
29
# File 'lib/redis/tracked_hash.rb', line 27

def deleted
  original.keys - self.keys
end

#dupObject



40
41
42
43
44
45
46
47
48
# File 'lib/redis/tracked_hash.rb', line 40

def dup
  dupe = super
  # duplicate a little deeper
  # otherwise, object references will make it appear a value hasn't changed when it has
  self.keys.each do |k|
    dupe[k] = self[k].dup rescue self[k]
  end
  dupe
end

#originalObject Also known as: track, track!



4
5
6
# File 'lib/redis/tracked_hash.rb', line 4

def original
  @original ||= self.dup
end

#populate(other_hash) ⇒ Object



35
36
37
38
# File 'lib/redis/tracked_hash.rb', line 35

def populate(other_hash)
  update(other_hash)
  retrack!
end

#retrackObject Also known as: retrack!



15
16
17
18
# File 'lib/redis/tracked_hash.rb', line 15

def retrack
  untrack!
  track!
end

#untrackObject Also known as: untrack!



10
11
12
# File 'lib/redis/tracked_hash.rb', line 10

def untrack
  @original = nil
end

#update(other_hash) ⇒ Object Also known as: merge!



50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/redis/tracked_hash.rb', line 50

def update(other_hash)
  if other_hash.kind_of?(TrackedHash)
    other_original = other_hash.original
    other_hash.instance_variable_set('@original',original)
    other_changed = other_hash.changed
    other_hash.deleted.each { |key| delete(key) }
    other_hash.instance_variable_set('@original',other_original)
    updates = Hash[ other_changed.map { |k| [k, other_hash[k]] } ]
    super( updates )
  else
    super
  end
end