What options do I have if I want to share data/attributes among Ruby Objects? [closed]

StackOverflow https://stackoverflow.com/questions/22410926

  •  14-06-2023
  •  | 
  •  

Pregunta

There are actually 2 cases here: 1)Objects are of the same type (for instance all are SomeClass objects), 2)Objects are not of the same type.

I am mostly interested in case 1. I tried to implement this using class variables but I read all over the internet to never use class variables (which I agree partially). What other ways are there to implement the same functionality?

¿Fue útil?

Solución

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
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top