1

I wrote a Ruby file my.rb, which has a module definition:

module MyModule
  ...
end

Another Ruby script requires my.rb on the fly, and I want to dynamically get the module name defined in my.rb. Is it possible?

sawa
  • 165,429
  • 45
  • 277
  • 381
TieDad
  • 9,143
  • 5
  • 32
  • 58
  • 1
    I'm sure this has been asked before, but i can't find it so I'll summarize. Yes you can do it with an approach such as getting the list of classes using [ObjectSpace.each_object](https://stackoverflow.com/questions/15852515/how-can-i-get-all-defined-classes), run the require,and then run it againn and see the difference. However it's worth reconsidering whether this is necessary, and if there's another way to do it. – max pleaner Mar 22 '18 at 01:48
  • 2
    What should the result be if there are multiple module definitions in the file? Or none? Or if there is a module definition, but the module has already been defined elsewhere? – Jörg W Mittag Mar 22 '18 at 08:28
  • 1
    Please, read [this post](https://meta.stackoverflow.com/q/270933/2988) on [meta], which explains why questions asking "is it possible" are poor questions and should be [edit]ed or closed. In general, ignoring special mathematical cases such as the Halting Problem, everything is always possible in some way or another, so the question does not contribute anything because the answer is trivial. Also, it is a Yes/No question, but neither a "Yes" nor a "No" answer actually helps you to solve your problem. Instead, you should describe your problem, describe the steps you took to solve it. – Jörg W Mittag Mar 22 '18 at 08:35

1 Answers1

1

You can use TracePoint to do that:

# :class is the start of a class or module definition
TracePoint.new(:class) do |trace|
  puts "defined a class or module named: #{trace.self}"
end.enable do
  require './my'
end

when running this script it will output:

defined a class or module named: MyModule

and only classes that get defined within the enable block get output

Simple Lime
  • 10,790
  • 2
  • 17
  • 32