In order to have data shared by all objects in the class, you can use either class variables or class instance variables.
Class variables are shared in the class hierarchy. This can have side effects that might break your expectations, as demonstrated in this example:
class A
@@common_data = :x
def common_computation
@@common_data
end
end
class B < A
@@common_data = :y
end
A.new.common_computation
# => y
B.new.common_computation
# => y
Class instance variables avoids that problem.
class A
class << self
attr_accessor :common_data
end
def common_computation
self.class.common_data
end
self.common_data = :x
end
class B < A
self.common_data = :y
end
A.new.common_computation
# => x
B.new.common_computation
# => y
You can use modules and mixins in order to share functionality and data.
module CommonFunctionality
attr_writer :common_data
def common_computation
# use @common_data
end
end
class A
include CommonFunctionality
end
class B
include CommonFunctionality
end
a = A.new
a.common_data = :x
a.common_computation
a.is_a? B # => false
a.kind_of? CommonFunctionality # => true
b = B.new
b.common_data = :y
b.common_computation
b.is_a? A # => false
b.kind_of? CommonFunctionality # => true