Module: Blur::Callbacks

Included in:
Client
Defined in:
library/blur/callbacks.rb

Instance Method Summary collapse

Instance Method Details

#callbacksObject

Get a list of callbacks registered.



8
9
10
# File 'library/blur/callbacks.rb', line 8

def callbacks
  @callbacks ||= {}
end

#emit(name, *args) ⇒ true, false

Emit a new event with given arguments.

Parameters:

  • name (Symbol)

    The event name.

  • args (optional, Array)

    The list of arguments to pass.

Returns:

  • (true, false)

    True if any callbacks were invoked, nil otherwise



17
18
19
20
21
22
23
24
25
26
27
# File 'library/blur/callbacks.rb', line 17

def emit name, *args
  # Trigger callbacks in scripts before triggering events in the client.
  EM.defer { notify_scripts name, *args }

  matching_callbacks = callbacks[name]
  return false unless matching_callbacks&.any?

  EM.defer do
    matching_callbacks.each { |callback| callback.call *args }
  end
end

#notify_scripts(name, *args) ⇒ Object (protected)



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'library/blur/callbacks.rb', line 39

def notify_scripts name, *args
  scripts = @scripts.values.select{|script| script.class.events.key? name }
  scripts.each do |script|
    begin
      script.class.events[name].each do |method|
        if method.is_a? Proc
          method.call script, *args
        else
          script.__send__ method, *args
        end
      end
    rescue => exception
      STDERR.puts "#{exception.class}: #{exception.message}"
      STDERR.puts nil, 'Backtrace:', '---', exception.backtrace
    end
  end
end

#on(name) {|args, ...| ... } ⇒ Object

Add a new event callback.

Parameters:

  • name (Symbol)

    The event name.

Yields:

  • (args, ...)

    The arguments passed from #emit.



33
34
35
# File 'library/blur/callbacks.rb', line 33

def on name, &block
  (callbacks[name] ||= []) << block
end