I have an external file: path_to_external_file.rbwith some class definition:
path_to_external_file.rb
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:
B
A
B::A
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?
Class.new{...}
include
You can not. At the very least, using loador require, Ruby files will always be evaluated in the upper context.
load
require
:
class B::A
eval(File.read("path_to_external_file.rb"))
: , : https://github.com/dreamcat4/script/blob/master/intro.txt
, , " 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
? " " , . . , , , , .