module RequireModule
Public Instance Methods
require_module(fullpath, cache: true)
click to toggle source
Evaluates file content inside Module.new and returns new module
Attributes¶ ↑
-
fullpath
- Absolute path to .rb file, .rb extension is optional
Options¶ ↑
-
:cache
- Default - true.
If false - creates new Module object with unique name. If true - creates new or returns already created Module with name, based on path to file
Examples¶ ↑
require_module('/home/user/rubyapp/lib', cache: false) # returns #<Module:0000012312> require_module('/home/user/rubyapp/lib') # returns :HomeUserRubyappLib
# File lib/require_module.rb 18 def require_module(fullpath, cache: true) 19 path = fullpath.to_s 20 with_ext = add_ext(path) 21 without_ext = rem_ext(path) 22 23 if cache 24 constant_name = 25 without_ext 26 .split(/[^a-zA-Z]/) 27 .map(&:capitalize) 28 .join 29 .to_sym 30 31 begin 32 Object.const_get(constant_name) 33 rescue NameError 34 mod = gen_mod(with_ext) 35 Object.const_set(constant_name, mod) 36 mod 37 end 38 else 39 gen_mod(with_ext) 40 end 41 end
require_module_relative(path, **options)
click to toggle source
Similar to “require_module”, but path is relative to file, where function is executed
Attributes¶ ↑
-
path
- Relative path to .rb file, .rb extension is optional
Options¶ ↑
-
:cache
- Default - true.
If false - creates new Module object with unique name. If true - creates new or returns already created Module with name, based on path to file
# File lib/require_module.rb 54 def require_module_relative(path, **options) 55 caller_filepath = caller_locations(1..1).first.absolute_path 56 caller_dir = File.dirname(caller_filepath) 57 58 fullpath = File.expand_path(path, caller_dir) 59 60 require_module(fullpath, **options) 61 end
Private Instance Methods
add_ext(path)
click to toggle source
# File lib/require_module.rb 79 def add_ext(path) 80 Pathname.new(path).sub_ext('.rb').to_s 81 end
gen_mod(fullpath)
click to toggle source
# File lib/require_module.rb 65 def gen_mod(fullpath) 66 content = read_rb(fullpath) 67 68 Module.new.tap do |mod| 69 mod.module_eval(content, fullpath, 1) 70 end 71 end
read_rb(fullpath)
click to toggle source
# File lib/require_module.rb 73 def read_rb(fullpath) 74 File.read(fullpath) 75 rescue Errno::ENOENT 76 raise LoadError, "path doesn't exist at #{fullpath}" 77 end
rem_ext(path)
click to toggle source
# File lib/require_module.rb 83 def rem_ext(path) 84 path.sub(/#{File.extname(path)}$/, '') 85 end