Question

I am still trying to clearly understand Module/Class/Instance variables ...

My code currently looks something like this ...

module Foo
  @@var1 ={}
  @@var2 =[]
  @@var3 = nil

  def m1(value)
    @@var2 << value
  end

  def m2(value)
    @@var1[@@var3]=value
  end
end

class Bar
  include Foo
  p @@var1
end

class Bar2
  include Foo
  p @var1
end

I am trying to create a module that contains a class-wide configuration for how each class will behave. The configuration is stored in @@var1 and @@var2. Using this code the variables are shared across ALL classes that include the module. This is not the desire result, I want each class to have it's own behavior configuration.

I have also tried creating a single class that includes the module and also creates the variables but then the variables are not accessible by the module.

module Foo

  def m1(value)
    @@var2 << value
  end

  def m2(value)
    @@var1[@@var3]=value
  end
end

class T
  @@var1 ={}
  @@var2 =[]
  @@var3 = nil

  include foo
end

class Bar < T
  p @@var1
end

class Bar2 < T
  p @var1
end

I have also read that having modules with class variables is not good coding style but I cannot think of a way to achieve my functionality with this ...

Thanks in advance for any help

Was it helpful?

Solution

Firstly - class variables are evil and should be avoided (because they are also inherited by all subclasses and usually causes more harm than good.

You want to create a class instance variable (not class variable) on a class or module which is including given module. It is easy to do with included method:

module Foo
  @default_settings = {}

  module ClassMethods
    def foo_settings
      @foo_settings
    end
  end

  def self.included(target)
    target.instance_variable_set('@foo_settings', @default_settings.dup)
    target.extend ClassMethods
  end    
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top