Jarmo Pertman wrote:
> Hello!
> 
> But the examples provided by you won't work since #constants return
> only immediate constants and not constants recursively. Thus:
> irb(main):003:0> module MyModule
> irb(main):004:1>   module AnotherModule
> irb(main):005:2>     class MyClass
> irb(main):006:3>     end
> irb(main):007:2>
> irb(main):008:2*     class AnotherClass
> irb(main):009:3>     end
> irb(main):010:2>   end
> irb(main):011:1> end
> => nil
> irb(main):012:0> MyModule.constants
> => ["AnotherModule"]

You can do the following:

>> module MyModule
>>   module AnotherModule
>>     class MyClass; end
>>     class AnotherClass; end
>>   end
>> end
=> nil
>> o = MyModule::AnotherModule::MyClass.new
=> #<MyModule::AnotherModule::MyClass:0xb7436be4>
>> o.class.name
=> "MyModule::AnotherModule::MyClass"
>> puts "Yippee" if o.class.name =~ /\bMyModule\b/
Yippee
=> nil
>> puts "Yippee" if o.class.name =~ /\bAnotherModule\b/
Yippee
=> nil

> So, both of you think that this solution would be best to do something
> like this? Or you're saying that i should not do something like this
> at all?

Modules are just namespaces. It seems odd to ask an object what 
namespace its class is in. As I've shown above, you can do this - but 
why would you want to?

The only time I've wanted to do anything close to this is dynamic 
constant resolution:

module X
  class Foo
    N=1
    def show_n
      puts self.class::N
    end
  end
  class Bar < Foo
    N=2
  end
end
X::Foo.new.show_n   # 1
X::Bar.new.show_n   # 2

But even then, neither Foo nor Bar cares whether it is inside module X. 
You can remove the module X wrapper completely, changing X::Foo.new to 
Foo.new, and it will work just the same.

Equally, if it *did* make a difference whether you were inside module X 
or module Y (perhaps because there were different constants or classes 
available), then you'd have to write your code differently within those 
modules anyway.

module X
  N=1
  class Foo
    def yo; puts N; end
  end
end
module Y
  M=2
  class Bar
    def yo; puts M; end
  end
end
-- 
Posted via http://www.ruby-forum.com/.