2

If (for whatever reason) I extend Stuff in class Dog how can I access CONST1 through the Dog class? I know I can get CONST1 by saying Stuff::CONST1, but how through dog can I get it. I also know that this code would work if I include Stuff in class Dog.

module Stuff 
  CONST1 = "Roll Over"
end

class Dog 
  extend Stuff  
end


Dog::CONST1 #NameError: uninitialized constant Dog::CONST1

3 Answers 3

4

You're probably thinking of include, not extend.

extend adds the instance methods:

Adds to obj the instance methods from each module given as a parameter.

but include:

Invokes Module.append_features on each parameter in reverse order.

and append_features:

Ruby‘s default implementation is to add the constants, methods, and module variables of this module to mod if this module has not already been added to mod or one of its ancestors.

So if you do this:

module M
  PANCAKES = 11
end

class C
  include M
end

Then you can get PANCAKES from C:

puts C::PANCAKES
# gives you 11
Sign up to request clarification or add additional context in comments.

Comments

2

From the documentation of extend:

Adds to obj the instance methods from each module given as a parameter.

It seems there is no reason to expect extend to add the constants.

3 Comments

It just seems odd that I might have a useful module ... and want its methods available as class methods for a class I have defined ... yet I cannot access the modules constants. The only way to access the constants is to include it, but I want the methods to be class methods... how can I do this?
...but I want the methods to be class methods... what do you mean by this? The methods you add to Stuff WILL be available as class methods to Dog if you extend. On your example, creating a method called test on Stuff will allow you to do Dog.test.
Yes, by using extend Stuffthe methods defined in the module Stuff will be class methods to Dog. What I am asking is... I would like to be able to be able use a modules methods as class methods on a given class. To accomplish this you use extend not include as include will make the methods instance methods. But what if there are CONSTANTS in that module that I am extending? It seems logical that I may need to access those CONSTANTS. The only way to access them is to include them.... but I don't want instance methods... I want class methods. Is it possible to access them?
1

Use:

module Stuff
  CONST1 = "Roll Over"
end

class Dog 
  include Stuff  
end


Dog::CONST1 # works

See What is the difference between include and extend in Ruby?

Comments

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.