Skip to content

Instantly share code, notes, and snippets.

@kronos
Created February 6, 2011 09:56
Show Gist options
  • Save kronos/813270 to your computer and use it in GitHub Desktop.
Save kronos/813270 to your computer and use it in GitHub Desktop.
class Class
def cattr_accessor(sym)
class_eval("unless defined? @@#{sym}\n@@#{sym} = nil\nend\n\ndef self.#{sym}=(obj)\n@@#{sym} = obj\nend\n", __FILE__, __LINE__ + 1)
class_eval("def self.#{sym}\n@@#{sym}\nend\n", __FILE__, __LINE__ + 1)
end
end
class A
cattr_accessor :attribute
end
class B
cattr_accessor :attribute
end
A.attribute = "PASS"
puts "A.attribute == #{A.class_variable_get(:@@attribute).inspect}"
puts "B.attribute == #{B.class_variable_get(:@@attribute).inspect}"
puts
B.attribute = "FAIL"
puts "A.attribute == #{A.class_variable_get(:@@attribute).inspect}"
puts "B.attribute == #{B.class_variable_get(:@@attribute).inspect}"
puts A.attribute
# 1.9.2 output:
# A.attribute == "PASS"
# B.attribute == nil
# A.attribute == "PASS"
# B.attribute == "FAIL"
# PASS
# Rubinius 1.2.1dev output:
# A.attribute == nil
# B.attribute == "PASS"
#
# A.attribute == nil
# B.attribute == "FAIL"
# FAIL
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment