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.



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

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.



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

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



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

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



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

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



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

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

#on_delete(&block) ⇒ Object



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

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

#on_destroy(&block) ⇒ Object



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

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

#on_update(&block) ⇒ Object



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

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