H
Hans Fugal
I have a simple observer-like module:
module Notifier
def add_notification(&callback)
@notifications = [] if not defined? @notifications
@notifications << callback
end
def delete_notification( &callback )
@notifications.delete(callback) if @notifications
end
protected
def notify
@notifications.each { |o| o.call } if defined? @notifications
end
end
(If 'Notifier' bugs you, then do a semantic search and replace
/notify/observe/)
I want to mix this in to a subclass of Array. The resulting class would
behave exactly like an Array except whenever the array changed notify
would be called.
I *could* subclass Array and def each of
&, *, +, --, <<, <=>, ==, ===, [], [], []=, assoc, at, clear,
collect, collect!, compact, compact!, concat, delete, delete_at,
delete_if, each, each_index, empty?, eql?, fill, first, flatten,
flatten!, include?, index, indexes, indices, join, last, length,
map!, new, nitems, pack, pop, push, rassoc, reject!, replace,
reverse, reverse!, reverse_each, rindex, shift, size, slice,
slice!, sort, sort!, to_a, to_ary, to_s, uniq, uniq!, unshift, |
that changes the Array, but obviously this isn't an exciting prospect.
I'm hoping that most of the changing methods of Array are actually
implemented in terms of a couple of fundamental methods, e.g. insert and
delete. So I would do:
class NotifyingArray
include Notifier
def insert(o)
super(o)
notify
end
def delete(o)
super(o)
notify
end
end
Am I on the right track? Does anyone know which methods I would have to
override?
module Notifier
def add_notification(&callback)
@notifications = [] if not defined? @notifications
@notifications << callback
end
def delete_notification( &callback )
@notifications.delete(callback) if @notifications
end
protected
def notify
@notifications.each { |o| o.call } if defined? @notifications
end
end
(If 'Notifier' bugs you, then do a semantic search and replace
/notify/observe/)
I want to mix this in to a subclass of Array. The resulting class would
behave exactly like an Array except whenever the array changed notify
would be called.
I *could* subclass Array and def each of
&, *, +, --, <<, <=>, ==, ===, [], [], []=, assoc, at, clear,
collect, collect!, compact, compact!, concat, delete, delete_at,
delete_if, each, each_index, empty?, eql?, fill, first, flatten,
flatten!, include?, index, indexes, indices, join, last, length,
map!, new, nitems, pack, pop, push, rassoc, reject!, replace,
reverse, reverse!, reverse_each, rindex, shift, size, slice,
slice!, sort, sort!, to_a, to_ary, to_s, uniq, uniq!, unshift, |
that changes the Array, but obviously this isn't an exciting prospect.
I'm hoping that most of the changing methods of Array are actually
implemented in terms of a couple of fundamental methods, e.g. insert and
delete. So I would do:
class NotifyingArray
include Notifier
def insert(o)
super(o)
notify
end
def delete(o)
super(o)
notify
end
end
Am I on the right track? Does anyone know which methods I would have to
override?