module Observer

A mixin to make it easier to implement observers using the standard observer library.

Mixing Observer into a class generates a default update method, which reacts to notification in the form of a hash, and calls appropriate event handlers, obtained by prepending “on_” to each key, and passing it the corresponding value.

For example, an event containing the following data

{ :pressed => { :x => 34, :y => 11 },
  :released => { :x => 10, :y => 76 } }

would result in the following method calls:

on_pressed(:x => 34, :y => 11)
on_released(:x => 10, :y => 76)

As a special case, if an event takes more than 1 parameter, the corresponding value is assumed to be an array, and its elements are passed as arguments to the event.

Public Instance Methods

update(data) click to toggle source

A default implementation for the update function.

Parses notification data and dispatches to the corresponding events.

# File lib/rui/observer_utils.rb, line 40
def update(data)
  data.each_key do |key|
    m = begin
      method("on_#{key}")
    rescue NameError
    end
    
    if m
      case m.arity
      when 0
        m[]
      when 1
        m[data[key]]
      else
        m[*data[key]]
      end
    end
  end
end