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.



103
104
105
106
# File 'lib/disposable/callback.rb', line 103

def initialize(twins)
  @twins = Array(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.



108
109
110
111
# File 'lib/disposable/callback.rb', line 108

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”?



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

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



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

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



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

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

#on_delete(&block) ⇒ Object



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

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

#on_destroy(&block) ⇒ Object



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

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

#on_update(&block) ⇒ Object



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

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