module Observable

Extensions to the standard Observable module of the observer library.

This mixin allows to define event handlers dynamically, without having to create an Observer class for each handler.

For example, assuming button is an instance of some observable class:

count = 0
button.on(:clicked) do
  count += 1
  puts "I have been clicked #{count} times"
end

Events can be fired with the fire method, and support arbitrary arguments.

Public Instance Methods

fire(e) click to toggle source

Fire an event.

@param e [Symbol, Hash] event and arguments. This needs to be either

a Symbol, or a Hash with a single key corresponding to the event, and the
value being the event data to pass to the handler.
# File lib/rui/observer_utils.rb, line 125
def fire(e)
  changed
  notify_observers any_to_event(e)
end
observe(event, &blk) click to toggle source

Create a dynamic observer handling a given event.

@param event [Symbol] the event to handle @param &blk [Block] event handler @return an observer object, which can be later used to remove

the event handler.
# File lib/rui/observer_utils.rb, line 94
def observe(event, &blk)
  obs = SimpleObserver.new(event, &blk)
  add_observer obs
  # return observer so that we can remove it later
  obs
end
observe_limited(event, &blk) click to toggle source

Create a limited observer handling a given event.

A limited observer behaves similarly to a normal dynamic observer, but in addition, it keeps track of the return valur of the handler. When the handler returns true, the observer is destroyed.

@param event [Symbol] the event to handle @param &blk [Block] event handler @return an observer object, which can be later used to remove

the event handler.
# File lib/rui/observer_utils.rb, line 112
def observe_limited(event, &blk)
  obs = LimitedObserver.new(self, event, &blk)
  add_observer obs
  obs
end
on(event, &blk) click to toggle source

Alias to observe.

# File lib/rui/observer_utils.rb, line 82
def on(event, &blk)
  observe(event, &blk)
end

Private Instance Methods

any_to_event(e) click to toggle source
# File lib/rui/observer_utils.rb, line 132
def any_to_event(e)
  if e.is_a? Symbol
    { e => nil }
  else
    e
  end
end