ruby picture

RCR 154: Observable objects always share observers after dup

Submitted by legacy (Fri Sep 26 00:09:15 UTC 2003)

Abstract

This is a legacy RCR from Ruby Garden, submitted by DaleFarnsworth. Matz has declared these RCRs obsolete, and asked that their authors resubmit them in the new format.

When you dup an object that includes the Observable module, the two objects always share the @observer_peers array. There is no way to have different observers for the two objects without adding a method to the Observable module. Since I doubt that there are many users of this feature, I propose that the delete_observers method be changed to:

class Observed
  def delete_observers
    @observer_peers = [] if @observer_peers
  end
end
Here's an example:

require "observer"
class Observed
  include Observable  attr_reader :str  def str=(str)
    changed
    notify_observers(str)
    @str = str
  end
end
class Observer
  def initialize(observed, prc)
    @observed = observed
    @prc = prc
    @observing = nil
    start
  end  def update(*args)
    @prc.call(*args)
  end  def start
    unless @observing
      @observed.add_observer(self)
      @observing = true
    end
  end  def stop
    if @observing
      @observed.delete_observer(self)
      @observing = false
    end
  end
end
a = Observed.new a_observer = Observer.new(a, proc {|arg| puts "a: #{arg}" })
puts "Test 1:" a.str = "One"
b = a.dup b.delete_observers b_observer = Observer.new(b, proc {|arg| puts "b: #{arg}" })
  1. unfortunately, a and b still share the same observers list

puts "Test 2:" a.str = "Two"
puts "Test 3:" b.str = "Three"
class Observed
  def delete_observers
    @observer_peers = [] if @observer_peers
  end
end
a = Observed.new a_observer = Observer.new(a, proc {|arg| puts "a: #{arg}" })
puts "Test 4:" a.str = "Four"
b = a.dup b.delete_observers b_observer = Observer.new(b, proc {|arg| puts "b: #{arg}" })
  1. Now, a and b have different observer lists

puts "Test 5:" a.str = "Five"
puts "Test 6:" b.str = "Six"
which results in this output:

Test 1:
a: One
Test 2:
b: Two
Test 3:
b: Three
Test 4:
a: Four
Test 5:
a: Five
Test 6:
b: Six

Problem

(RCR imported from old format)

Proposal

Analysis

(RCR imported from old format)

Implementation

(RCR imported from old format)
ruby picture
Comments Current voting


Strongly opposed 0
Opposed 0
Neutral 0
In favor 0
Strongly advocate 0
ruby picture
If you have registered at RCRchive, you may now sign in below. If you have not registered, you may sign up for a username and password. Registering enables you to submit new RCRs, and vote and leave comments on existing RCRs.
Your username:
Your password:

ruby picture

Powered by .