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
slindsey3000
  • 4,053
  • 5
  • 36
  • 56

3 Answers3

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
mu is too short
  • 426,620
  • 70
  • 833
  • 800
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.

ryantm
  • 8,217
  • 6
  • 45
  • 57
  • 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? – slindsey3000 Sep 29 '11 at 18:48
  • `...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`. – derp Sep 29 '11 at 21:10
  • Yes, by using `extend Stuff`the 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? – slindsey3000 Sep 30 '11 at 00:59
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?

Community
  • 1
  • 1
duncan
  • 6,113
  • 3
  • 29
  • 24