Florian Frank
1/15/2007 4:11:00 PM
Juozas Gaigalas wrote:
> I'm looking for a simple and short solution/library that does this:
>
> a = []
>
> def a.modified
> puts "Array a changed"
> end
>
> a << 'x'
> puts a
> a[0] = 'y'
> puts a
>
> ----OUTPUT----
> Array a changed
> x
> Array a changed
> y
>
>
class Changed
def initialize(obj, &changed)
@obj = obj
@changed = changed
end
def method_missing(id, *a, &b)
obj_before = @obj.clone
@obj.__send__(id, *a, &b)
if obj_before != @obj
@changed[@obj, id, a, b]
end
end
end
if $0 == __FILE__
a = []
c = Changed.new(a) do |obj, id, args, block|
STDOUT << "#{obj.inspect} changed by #{id}"
STDOUT << "(#{args.map { |x| x.inspect } * ','})" unless args.empty?
STDOUT << "\n"
end
c << 1
# [1] changed by <<(1)
c.to_s
c << 2
# [1, 2] changed by <<(2)
c.delete 2
# [1] changed by delete(2)
c.delete 2
c << 3
# [1, 3] changed by <<(3)
c[0] = 4
# [4, 3] changed by []=(0,4)
c.replace [6,6,6]
# [6, 6, 6] changed by replace([6, 6, 6])
c.clear
# [] changed by clear
end
--
Florian Frank