title: Ruby: Inherit code that works with class variables
body: <p>The situation: I have multiple classes that should each hold a variable with a configuration hash; a different hash for each class but the same for all instances of a class.</p>
  
  <p>At first, i tried like this</p>
  
  <pre><code>class A
    def self.init config
      @@config = config
    end
  
    def config
      @@config
    end
  end
  
  class B &lt; A; end
  class C &lt; A; end
  </code></pre>
  
  <p>But soon noticed that it wouldn't work that way because @@config is held in the context of A, not B or C, thus:</p>
  
  <pre><code>B.init "bar"
  p B.new.config  # =&gt; "bar"
  p C.new.config  # =&gt; "bar" - which would be nil if B had it's own @@config
  
  C.init "foo"
  p B.new.config  # =&gt; "foo" - which would still be "bar" if C had it's own @@config
  p C.new.config  # =&gt; "foo"
  </code></pre>
  
  <p>I thought of using it like this:</p>
  
  <pre><code>modules = [B, C]
  modules.each do |m|
    m.init(@config[m.name])
  end
  # ...
  B.new  # which should then have the correct config
  </code></pre>
  
  <p>Now, it's clear to me why that happens, but I'm not sure about the reason for it being like this.</p>
  
  <p>Couldn't it work the other way too, holding the class variable in the context of the subclass?</p>
  
  <p>What i also found irritating was the fact that self is always the subclass even when called 'in' the superclass. From this, I first expected the code from the superclass is "executed in the context of" the subclass.</p>
  
  <p>Some enlightenment about this would be greatly appreciated.</p>
  
  <p>On the other hand, I likely have to accept it works that way and that I have to find another way to do this.</p>
  
  <p>Is there a "meta" way to do this? (I tried with class_variable_set etc. but with no luck)</p>
  
  <p>Or maybe is the whole idea of that 'init' method flawed in the first place and there's some other "pattern" to do this?</p>
  
  <p>I could just make @@config a hash, holding all the configs and always pick the right one, but I find that a little awkward.. (isn't inheritance there to solve this kind of problem? ;)</p>