Retrieving a class module is defined without string manipulation

Reference ( Ruby module name from class defined in , Module.nesting inside instance_eval / exec or module_eval / exec )

In the following setup:

module Foo
  class Bar
  end
end

      

Is there a way to get the name of the module Foo

without having to change Bar

and without resorting to string manipulation with the fully qualified name Foo::Bar

?

+3


source to share


1 answer


I am cheating, I am not changing Bar

, but Class

:



class Class
  def my_module
    self.to_s.split('::').first
  end
end 

module Foo
  class Bar    
  end
end

p Foo::Bar.my_module  #-> "Foo"

#Works also after include
include Foo
p Bar.my_module #-> "Foo"

      

0


source







All Articles