Sample code (based on fragment from
rails/actionpack/test/abstract_unit.rb):
module A
class Sample; end
module Incorrect; end
module Correct; end
class << Sample; def list; @@list ||= []; end; end
class << Incorrect; def list; @@list ||= []; end; end # original
pattern
module Correct; def self.list; @@list ||= []; end; end
end
def test_m(obj)
2.times do |i|
l = obj.list
l << “test”
printf “%d) %s %d %s\n”, i, obj.name, l.object_id, l.inspect
end
end
[A::Incorrect, A::Correct, A::Sample].each {|mod| test_m(mod) }
Output:
ruby 1.8.7 (2009-09-11 patchlevel 202) [i686-linux]:
0) A::Incorrect -603619398 [“test”]
- A::Incorrect -603619398 [“test”, “test”]
- A::Correct -603619548 [“test”]
- A::Correct -603619548 [“test”, “test”]
- A::Sample -603619398 [“test”, “test”, “test”]
- A::Sample -603619398 [“test”, “test”, “test”, “test”]
ruby 1.9.2dev (2009-09-28 trunk 25126) [i686-linux]:
0) A::Incorrect 79250400 [“test”]
- A::Incorrect 79250300 [“test”]
- A::Correct 79250220 [“test”]
- A::Correct 79250220 [“test”, “test”]
- A::Sample 79250060 [“test”]
- A::Sample 79249980 [“test”]
So, the question is, what is the correct way to declare and use such
constructs, and what caused the problem – bug in ruby or incorrect
use of class variables?