1

I'm attempting to include a method from a module in a class, and have the method that is included access a class variable of the base class that's doing the including, but it's not working like I assumed. Code:

class Awesome
    @@name = "ME!"
end

module MyGem
    module Namespace
        def typist
            puts @@name
        end
    end
end

if defined? Awesome
    Awesome.class_eval do
        include MyGem::Namespace
    end
end

Awesome.new.typist # Test our new 'injected' instance method!
#=> NameError: uninitialized class variable @@name in MyGem::Namespace

Clearly my understanding of Ruby's include behaviour is wonky, I thought include would incorporate the method(s) into the base class and the execution context would be the base class, but the error message seems to imply the execution context of included methods is in the original method's module.

So how can I achieve what I'd like to do as illustrated in my code snippet? Mind you, I'm more than happy to replace the class variable with any other implementation, such as using instance variables, or however which it takes to make it work :).

1 Answer 1

1

If you make the class variable lookup the result of a method call, it works:

def typist
  puts self.class.class_variable_get(:@@name)
end

I'm afraid I'm not familiar enough with class variables to explain why it works this way but not the other. I do know that class variables are relatively unpopular in the Ruby world, mostly for the reason that their behavior can be unpredictable. My gut feeling is that since you can define class variables in a module (classes inherit from Module, after all), referring to the variable in a module automatically searches within that module. Explicitly sending the lookup message to the class of the instance to which you are sending :typist ensures the correct variable is found.

Sign up to request clarification or add additional context in comments.

5 Comments

your answer is not addressing the problem of the topic.
@sunny1304, Can you be more specific?
I mean the code u provided inlcudes class_variale_get method...using that the code will work for sure....but we need to know why without class_variable_get the code is not working.
Okay, so the first occurrence of class should actually be replaced with "self.class", or else you will get an exception telling you that the "." after class is misplaced.
@TahitiPetey, my interpreter worked without it, but you're right - in general that probably good practice.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.