2

I am trying to understand module inclusions with class variables. I thought that including a module with class variables would also include the class variables into the class definition.

This works as intended:

module A 
  @@my_name = "rick"
  def print_name
    puts @@my_name
  end
end

class Y 
  include A
  extend A
end

Y.print_name

But this does not:

module A

  def self.included(klass)
    klass.include B
    klass.extend C
  end

  module B
    @@my_name = "bob"
  end

  module C 
    def print_name
      puts @@my_name
    end
  end

end

class Y
  include A
end

Y.print_name

I was expecting "bob" but instead i got:

uninitialized class variable @@my_name in A::C

d0bz
  • 165
  • 9

2 Answers2

1

It would work if you use Module#class_variable_get:

module C
  def print_name
    class_variable_get(:@@my_name)
  end
end
Y.print_name
#=> "bob"

I think the problem was that when in module C you say puts @@my_name it does not yet know about the @@my_name, because in module C you have never set it (it is set in module B and C does not know about B).

Andrey Deineko
  • 51,333
  • 10
  • 112
  • 145
-1

What if you try to prepend the module? That adds a module to a class, but inserts them BEFORE the class's methods. This is a way to ensure that if there is a variable naming conflict, the module will win-out.

And I mean this more as a comment, but my user rating isn't high enough yet for comments, so I apologize if this is off the mark.

Spectator6
  • 363
  • 1
  • 5
  • 19