Dynamically determining a class' namespace

D

Daniel Berger

Hi all,

Ruby 1.8.x

Is there a way to determine a classes namespace from within an
instance method?

class Foo
def initialize
# print namespace
end
end

Foo.new # 'Object'? 'Kernel'? nil?

module Bar
Foo.new # 'Bar'
end

module Baz
module Bar
Foo.new # 'Baz::Bar'
end
end

If not, is it possible at the class level? I looked at Module#nesting
and Module#name, but I couldn't see how to use those to get what I
want.

Thanks,

Dan
 
A

ara.t.howard

Hi all,

Ruby 1.8.x

Is there a way to determine a classes namespace from within an
instance method?

class Foo
def initialize
# print namespace
end
end

Foo.new # 'Object'? 'Kernel'? nil?

module Bar
Foo.new # 'Bar'
end

module Baz
module Bar
Foo.new # 'Baz::Bar'
end
end

If not, is it possible at the class level? I looked at Module#nesting
and Module#name, but I couldn't see how to use those to get what I
want.

Thanks,

Dan

http://groups.google.com/group/comp...&q=a.rb+nesting&rnum=2&hl=en#c1fb423d3dcda20e

-a
 
M

Mauricio Fernandez

harp:~ > cat a.rb
require 'binding_of_caller'

class Foo
def self.new
Binding.of_caller{|b| p eval('Module.nesting', b).shift }
end
end

Foo.new # 'Object'? 'Kernel'? nil?

module Bar
Foo.new # 'Bar'
end

module Baz
module Bar
Foo.new # 'Baz::Bar'
end
end

harp:~ > ruby a.rb
nil
Bar
Baz::Bar

$ ruby -v a.rb
ruby 1.8.5 (2006-08-25) [i686-linux]
nil
nil
nil

(Foo with 1.8.5-p12)

1.8.5 killed Binding.of_caller, take a look at ruby-debug
http://rubyforge.org/projects/ruby-debug/.

--
Mauricio Fernandez - http://eigenclass.org - singular Ruby
** Latest postings **
Ruby, SEX and STDs: infectious practices
http://eigenclass.org/hiki.rb?ruby-warnings-SEX-and-stds
What's new in Ruby 1.9, Feb. 07 update
http://eigenclass.org/hiki.rb?Changes-in-Ruby-1.9-update-6
 

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,013
Latest member
KatriceSwa

Latest Threads

Top