Class: Brainguy::OpenObserver

Inherits:
Object
  • Object
show all
Defined in:
lib/brainguy/open_observer.rb

Overview

A quick and dirty way to set up a reusable listener object. Like an OpenObject, only for event listening!

Instance Method Summary collapse

Constructor Details

#initialize(handlers = {}) {|self| ... } ⇒ OpenObserver

end

Examples:

Initializing and then adding handlers dynamically

ol = OpenObserver.new
ol.on_foo do
  # ...
end
ol.on_bar do
  # ...
end

Initializing with a block

listener = OpenObserver.new do |ol|
  ol.on_foo do
    # ...
  end
  ol.on_bar do
    # ...
  end

Initializing from a hash

listener = OpenObserver.new(foo: ->{...}, bar: ->{...})

Parameters:

  • handlers (Hash{Symbol => [:call]}) (defaults to: {})

    a Hash of event names to callable handlers

Yields:

  • (self)

    if a block is given



27
28
29
30
# File 'lib/brainguy/open_observer.rb', line 27

def initialize(handlers = {})
  @handlers = handlers
  yield self if block_given?
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method_name, *_args, &block) ⇒ Object

Enable setting up event handlers dynamically using on_* message sends.

Examples:

ol = OpenObserver.new
ol.on_foo do
  # ...
end
ol.on_bar do
  # ...
end


50
51
52
53
54
55
56
57
# File 'lib/brainguy/open_observer.rb', line 50

def method_missing(method_name, *_args, &block)
  if method_name.to_s =~ /\Aon_(.+)/
    @handlers[$1.to_sym] = block
    self
  else
    super
  end
end

Instance Method Details

#call(event) ⇒ Object

Dispatch the event to the appropriate handler, if one has been set. Events without handlers are ignored.

Parameters:

  • event (Event)

    the event to be handled



35
36
37
38
39
# File 'lib/brainguy/open_observer.rb', line 35

def call(event)
  if (handler = @handlers[event.name])
    handler.call(event)
  end
end

#respond_to_missing?(method_name, _include_private) ⇒ Boolean

true if the method starts with on_

Returns:

  • (Boolean)


61
62
63
# File 'lib/brainguy/open_observer.rb', line 61

def respond_to_missing?(method_name, _include_private)
  method_name.to_s =~ /\Aon_./
end