Module: Observables::HashWatcher

Includes:
Base
Included in:
Hash
Defined in:
lib/observables/hash_watcher.rb

Constant Summary collapse

MODIFIER_METHODS =
:replace, :merge!, :update
REMOVE_METHODS =
:clear, :delete, :delete_if, :reject!, :shift

Instance Method Summary collapse

Instance Method Details

#[]=(key, val) ⇒ Object Also known as: store

[]= can either be an add method or a modifier method depending on if the previous key exists



10
11
12
13
14
# File 'lib/observables/hash_watcher.rb', line 10

def []=(key,val)
  change_type = keys.include?(key) ? :modified : :added
  changes = changes_for(change_type,:[]=,key,val)
  changing(change_type,:trigger=>:[]=, :changes=>changes) {super}
end

#changes_for(change_type, trigger_method, *args, &block) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/observables/hash_watcher.rb', line 20

def changes_for(change_type, trigger_method, *args, &block)
  prev = self.dup
  if change_type == :added
    lambda {{:added=>[args]}}
  elsif change_type == :removed
    case trigger_method
      when :clear then lambda{{:removed=>prev.to_a}}
      when :delete then lambda{{:removed=>[[args[0],prev[args[0]]]]}}
      when :delete_if, :reject! then lambda{{:removed=>prev.select(&block)}}
      when :shift then lambda { {:removed=>[prev.keys[0],prev.values[0]]}}
    end
  else
    case trigger_method
      when :[]= then lambda{{:removed=>[[args[0],prev[args[0]]]],:added=>[args]}}
      when :replace then lambda{{:removed=>prev.to_a, :added=>args[0].to_a}}
      when :merge!, :update then lambda{{:removed=>prev.select{|k,_|args[0].keys.include?(k)},:added=>args[0].to_a}}
    end
  end
end