On Dec 16, 9:25 am, Brubix <bruno.bazz... / tin.it> wrote:
> I can't figure out how to set class variables from class methods
> inherited from a module ?
>
> The following doesn't work as I expected (I spare you my others
> pathetic attempts):
>
> module MyModule
>         def self.extended(base)
>                 base.setClassVar(base.name.downcase)
>         end
>         def setClassVar(value)
>                 puts "self is #{self.name}"
>                 puts "@@classVar=#{value}"
>                 @@classVar = value
>         end
>         def getClassVar
>                 @@classVar
>         end
> end
>
> class Class1
>         extend MyModule
> end
> class Class2
>         extend MyModule
> end
>
> puts "classVar for Class1 is " + Class1.getClassVar
> puts "classVar for Class2 is " + Class2.getClassVar
>
> It gives:
> self is Class1
> @@classVar=class1
> self is Class2
> @@classVar=class2
> classVar for Class1 is class2    # Shouldn't be class1 ?!
> classVar for Class2 is class2
>
> Many thanks in advance.
>
> Brubix

Use Module#class_variable_get/set for this kind of thing.

module MyModule
  def self.extended(base)
    base.setClassVar(base.name.downcase)
  end
  def setClassVar(value)
    puts "self is #{self.name}"
    puts "@@classVar=#{value}"
    class_variable_set(:@@classVar, value)
  end
  def getClassVar
    class_variable_get(:@@classVar)
  end
end

HTH,
Jordan