u-observers 0.7.0 → 2.1.0

Sign up to get free protection for your applications and to get access to all the features.
@@ -1,93 +0,0 @@
1
- # frozen_string_literal: true
2
-
3
- module Micro
4
- module Observers
5
-
6
- class Manager
7
- EqualTo = -> (observer) do
8
- -> item { item[0] == :observer && item[1] == observer }
9
- end
10
-
11
- def self.for(subject)
12
- new(subject)
13
- end
14
-
15
- def initialize(subject, list = nil)
16
- @subject = subject
17
-
18
- @list = Utils.compact_array(list.kind_of?(Array) ? list : [])
19
- end
20
-
21
- def included?(observer)
22
- @list.any?(&EqualTo[observer])
23
- end
24
-
25
- def attach(*args)
26
- options = args.last.is_a?(Hash) ? args.pop : Utils::EMPTY_HASH
27
-
28
- Utils.compact_array(args).each do |observer|
29
- if options[:allow_duplication] || !included?(observer)
30
- @list << [:observer, observer, options[:data]]
31
- end
32
- end
33
-
34
- self
35
- end
36
-
37
- def on(options = Utils::EMPTY_HASH)
38
- event, callable, with = options[:event], options[:call], options[:with]
39
-
40
- return self unless event.is_a?(Symbol) && callable.respond_to?(:call)
41
-
42
- arg = with.is_a?(Proc) ? with.call(@subject) : (arg || subject)
43
-
44
- @list << [:callable, event, [callable, arg]]
45
- end
46
-
47
- def detach(*args)
48
- Utils.compact_array(args).each do |observer|
49
- @list.delete_if(&EqualTo[observer])
50
- end
51
-
52
- self
53
- end
54
-
55
- def notify(*events)
56
- broadcast(EventsOrActions[events])
57
-
58
- self
59
- end
60
-
61
- def call(options = Utils::EMPTY_HASH)
62
- broadcast(EventsOrActions.fetch_actions(options))
63
-
64
- self
65
- end
66
-
67
- private
68
-
69
- def broadcast(evts_or_acts)
70
- evts_or_acts.each do |evt_or_act|
71
- @list.each do |strategy, observer, data|
72
- call!(observer, strategy, data, with: evt_or_act)
73
- end
74
- end
75
- end
76
-
77
- def call!(observer, strategy, data, with:)
78
- return data[0].call(data[1]) if strategy == :callable && observer == with
79
-
80
- if strategy == :observer && observer.respond_to?(with)
81
- handler = observer.method(with)
82
-
83
- return handler.call(@subject) if handler.arity == 1
84
-
85
- handler.call(@subject, data)
86
- end
87
- end
88
-
89
- private_constant :EqualTo
90
- end
91
-
92
- end
93
- end