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

Returns a new instance of Dispatch.



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

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

Instance Method Details

#call(event, method, *args, &block) ⇒ Object

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



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

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

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

how to call it once, for “all”?



120
121
122
123
124
125
126
# File 'lib/disposable/callback.rb', line 120

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.nil?
    run!(item, &block) if item.created? && state == :created # :created # DISCUSS: should we really keep that?
  end
end

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



157
158
159
160
161
162
163
164
165
166
167
168
169
# File 'lib/disposable/callback.rb', line 157

def on_change(options={}, &block)
  name = 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



150
151
152
153
154
155
# File 'lib/disposable/callback.rb', line 150

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

#on_delete(&block) ⇒ Object



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

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

#on_destroy(&block) ⇒ Object



135
136
137
138
139
# File 'lib/disposable/callback.rb', line 135

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

#on_update(&block) ⇒ Object



141
142
143
144
145
146
147
148
# File 'lib/disposable/callback.rb', line 141

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