Loading external files inside a class / module

I have an external file: path_to_external_file.rbwith some class definition:

class A
  some_definitions
end

And I want to load this into a module Bso that the class described above Acan be called B::A. I tried:

class B
  load('path_to_external_file.rb')
end

but Adefined in the main environment, not in B:

A #=> A
B.constants # => []

How to load external files into some class / module?

Edit Do I have to read external files as strings and evaluate them within Class.new{...}and includethat class inside B?

+5
source share
2 answers

You can not. At the very least, using loador require, Ruby files will always be evaluated in the upper context.

:

  • class B::A ( , , )
  • eval(File.read("path_to_external_file.rb")) B

: , : https://github.com/dreamcat4/script/blob/master/intro.txt

+4

, , " A", " " B. A B:: A, ,

module B
  class A
    # contents
  end
end

class B::A
  # contents
end

, , . , , "", . : Ruby , . , - . .

, , , - . , , :

m = Module.new
m.module_eval("class C; end")
m.constants
=> [:C]
m.const_get(:C)
=> #<Module:0xfd0da0>::C

? " " , . . , , , , .

+3

All Articles