Module: Observables::ArrayWatcher

Includes:
Base
Included in:
Array
Defined in:
lib/observables/array_watcher.rb

Constant Summary collapse

ADD_METHODS =
:<<, :push, :concat, :insert, :unshift
MODIFIER_METHODS =
:collect!, :map!, :flatten!, :replace, :reverse!, :sort!, :fill
REMOVE_METHODS =
:clear, :compact!, :delete, :delete_at, :delete_if, :pop, :reject!, :shift, :slice!, :uniq!

Instance Method Summary collapse

Instance Method Details

#[]=(*args) ⇒ Object

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



12
13
14
15
16
# File 'lib/observables/array_watcher.rb', line 12

def []=(*args)
  change_type = args[0] >= length ? :added : :modified
  changes = changes_for(change_type,:"[]=",*args)
  changing(change_type,:trigger=>:"[]=", :changes=>changes) {super}
end

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



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/observables/array_watcher.rb', line 22

def changes_for(change_type, trigger_method, *args, &block)
  prev = self.dup.to_a
  if change_type == :added
    case trigger_method
      when :"[]=" then lambda {{:added=>args[-1]}}
      when :<<, :push, :unshift then lambda {{:added=>args}}
      when :concat then lambda {{:added=>args[0]}}
      when :insert then lambda {{:added=>args[1..-1]}}
      else lambda { |cur| {:added=>(cur - prev).uniq }}
    end
  elsif change_type == :removed
    case trigger_method
      when :delete then lambda {{:removed=>args}}
      when :delete_at then lambda {{:removed=>[prev[args[0]]]}}
      when :delete_if, :reject! then lambda {{:removed=>prev.select(&block)}}
      when :pop then lambda {{:removed=>[prev[-1]]}}
      when :shift then lambda {{:removed=>[prev[0]]}}
      else lambda { |cur| {:removed=>(prev - cur).uniq }}
    end
  else
    case trigger_method
      when :replace then lambda {{:removed=>prev, :added=>args[0]}}
      when :"[]=" then lambda {{:removed=>[prev[*args[0..-2]]].flatten, :added=>[args[-1]].flatten}}
      else lambda {|cur|{:removed=>prev.uniq, :added=>cur}}
    end
  end
end