I'm a frog dragon
I'm a frog dragon

Reputation: 8895

Where should I put the `include` statement?

I'm trying to use a module as a namespace for my constants. Let's say I have a module like this:

module AnimalModule
  Dog = 1
end

and a class called PetStore that uses the module. Where should I place the include statement?

(1) Is it like this:

# PetStore.rb
include AnimalModule
class PetStore
end

(2) or like this:

# PetStore.rb
class PetStore
  include AnimalModule
end

I try to use the the constant in my class's instance method, and both way seem to work the same:

class PetStore
  def feed
    puts Dog
  end 
end

Upvotes: 1

Views: 109

Answers (2)

halfelf
halfelf

Reputation: 10107

The second style is the right choice. The difference is the scope of Dog. The first one includes the module in a larger scope. So it works in your example too. But it will not provide the namespace you want.

module AnimalModule
  Dog = 1
end
class PetStore
  include AnimalModule
end
Dog # => NameError: uninitialized constant Dog
PetStore::Dog # => 1

include AnimalModule
Dog # => 1

Upvotes: 2

Hunter McMillen
Hunter McMillen

Reputation: 61550

You include modules after the class just like you did in your second block of code:

C:\Users\Hunter>irb
irb(main):001:0> module AnimalModule
irb(main):002:1>   Dog = 1
irb(main):003:1> end
=> 1
irb(main):004:0> class PetStore
irb(main):005:1>   include AnimalModule
irb(main):006:1>   def feed
irb(main):007:2>     puts Dog
irb(main):008:2>   end
irb(main):009:1> end
=> nil
irb(main):010:0> p = PetStore.new()
=> #<PetStore:0x25e07b0>
irb(main):011:0> p.feed
1
=> nil

I used your code in the interactive interpreter and got 1 as the result of calling the feed() method.

Upvotes: 2

Related Questions