Module: Denko::Behaviors::Callbacks

Constant Summary

Constants included from Lifecycle

Lifecycle::CALLBACK_METHODS

Instance Attribute Summary

Attributes included from State

#state

Instance Method Summary collapse

Methods included from State

#update_state

Methods included from Lifecycle

included

Instance Method Details

#add_callback(key = :persistent, &block) ⇒ Object Also known as: on_data



16
17
18
19
20
21
22
23
# File 'lib/denko/behaviors/callbacks.rb', line 16

def add_callback(key=:persistent, &block)
  @callback_mutex.lock
  @callbacks      ||= {}
  @callbacks[key] ||= []
  @callbacks[key] << block
  @callback_mutex.unlock
  @callbacks
end

#callbacksObject



12
13
14
# File 'lib/denko/behaviors/callbacks.rb', line 12

def callbacks
  @callbacks ||= {}
end

#pre_callback_filter(data) ⇒ Object

Override to process data before giving to callbacks and state.



66
67
68
# File 'lib/denko/behaviors/callbacks.rb', line 66

def pre_callback_filter(data)
  data
end

#remove_callback(key = nil) ⇒ Object Also known as: remove_callbacks



25
26
27
28
29
30
# File 'lib/denko/behaviors/callbacks.rb', line 25

def remove_callback(key=nil)
  @callback_mutex.lock
  (@callbacks && key) ? @callbacks.delete(key) : @callbacks = {}
  @callback_mutex.unlock
  @callbacks
end

#update(data) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/denko/behaviors/callbacks.rb', line 35

def update(data)
  # nil will unblock #read without running callbacks.
  unless data
    remove_callback(:read)
    return nil
  end

  filtered_data = pre_callback_filter(data)

  # nil will unblock #read without running callbacks.
  unless filtered_data
    remove_callback(:read)
    return nil
  end

  @callback_mutex.lock
  if @callbacks && !@callbacks.empty?
    @callbacks.each_value do |array|
      array.each do |callback|
        callback.call(filtered_data)
      end
    end
    # Remove one-time callbacks added by #read.
    @callbacks.delete(:read)
  end
  @callback_mutex.unlock

  update_state(filtered_data)
end