Class: Disposable::Callback::Dispatch

Inherits:
Object
  • Object
show all
Defined in:
lib/disposable/callback.rb

Overview

Invokes callback for one event, e.g. on_add(:relax!). Implements the binding between the Callback API (on_change) and the underlying layer (twin/AR/etc.).

Instance Method Summary collapse

Constructor Details

#initialize(twins) ⇒ Dispatch



105
106
107
108
# File 'lib/disposable/callback.rb', line 105

def initialize(twins)
  @twins = Array(twins) # TODO: find that out with Collection.
  @invocations = []
end

Instance Method Details

#call(event, method, property_options, &block) ⇒ Object

FIXME: as long as we only support method, pass in here.



110
111
112
113
# File 'lib/disposable/callback.rb', line 110

def call(event, method, property_options, &block) # FIXME: as long as we only support method, pass in here.
  send(event, property_options, &block)
  [event, method, @invocations]
end

#on_add(state = nil, &block) ⇒ Object

how to call it once, for “all”?



115
116
117
118
119
120
121
# File 'lib/disposable/callback.rb', line 115

def on_add(state=nil, &block) # how to call it once, for "all"?
  # @twins can only be Collection instance.
  @twins.added.each do |item|
    run!(item, &block) if ! state.is_a?(Symbol)
    run!(item, &block) if item.created? && state == :created # :created # DISCUSS: should we really keep that?
  end
end

#on_change(property_options = {}, &block) ⇒ Object



152
153
154
155
156
157
158
159
160
161
162
163
164
# File 'lib/disposable/callback.rb', line 152

def on_change(property_options={}, &block)
  name = property_options[:property]

  @twins.each do |twin|
    if name
      run!(twin, &block) if twin.changed?(name)
      next
    end

    next unless twin.changed?
    run!(twin, &block)
  end
end

#on_create(&block) ⇒ Object



145
146
147
148
149
150
# File 'lib/disposable/callback.rb', line 145

def on_create(*, &block)
  @twins.each do |twin|
    next unless twin.created?
    run!(twin, &block)
  end
end

#on_delete(&block) ⇒ Object



123
124
125
126
127
128
# File 'lib/disposable/callback.rb', line 123

def on_delete(*, &block)
  # @twins can only be Collection instance.
  @twins.deleted.each do |item|
    run!(item, &block)
  end
end

#on_destroy(&block) ⇒ Object



130
131
132
133
134
# File 'lib/disposable/callback.rb', line 130

def on_destroy(*, &block)
  @twins.destroyed.each do |item|
    run!(item, &block)
  end
end

#on_update(&block) ⇒ Object



136
137
138
139
140
141
142
143
# File 'lib/disposable/callback.rb', line 136

def on_update(*, &block)
  @twins.each do |twin|
    next if twin.created?
    next unless twin.persisted? # only persisted can be updated.
    next unless twin.changed?
    run!(twin, &block)
  end
end