including a namespace for just one class

S

S. Robert James

I would like to reference constants and classes defined in module
People in the class Schedule.

class Login is not part of any module (other than the root).

doing this:
class Schedule
include People
def a_method
# Worker.new won't work
People::Worker.new # works
end
end

doesn't work.

Is there a way to include the module People so that I don't need to
prefix People:: for only one particular class?

Also, why doesn't what I tried work? Doesn't include copy in the
constants, and aren't classes just constants?
 
M

Morton Goldberg

I would like to reference constants and classes defined in module
People in the class Schedule.

class Login is not part of any module (other than the root).

doing this:
class Schedule
include People
def a_method
# Worker.new won't work
People::Worker.new # works
end
end

Is there a way to include the module People so that I don't need to
prefix People:: for only one particular class?

I don't know why it doesn't work for you -- it works fine for me.

<code>
module People
class Worker
end
end

class Schedule
include People
def a_method
p Worker.new
end
end

Schedule.new.a_method
</code>

<results>
#<People::Worker:0x88494>
</results>

Regards, Morton
 
P

Phrogz

I would like to reference constants and classes defined in module
People in the class Schedule.

Here's an example that works fine for me:
module People
POPULATION = 1234567
end

class Schedule
include People
def x
p POPULATION
end
end

s = Schedule.new
s.x
#=> 1234567

p VERSION
#=> "1.8.5"
 
S

S. Robert James

Is it possible that Rails changes things somehow?
I think I know - the autoloader can't find them then!
 
S

S. Robert James

S. Robert James said:
Is it possible that Rails changes things somehow?
I think I know - the autoloader can't find them then!

Does that make any sense? The autoloader can find them if I include
People in the global namespace, but not if I include it in the class?!
If so, is there a workaround?
 
L

Logan Capaldo

Does that make any sense? The autoloader can find them if I include
People in the global namespace, but not if I include it in the class?!
If so, is there a workaround?
Yes it makes sense and you are probably right. The workaround is to
explicitly require the file

e.g:
require 'people' # Or whatever the file is
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,020
Latest member
GenesisGai

Latest Threads

Top