Module: RequireModule

Defined in:
lib/require_module.rb

Instance Method Summary collapse

Instance Method Details

#require_module(fullpath, cache: true) ⇒ Object

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


18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/require_module.rb', line 18

def require_module(fullpath, cache: true)
  path = fullpath.to_s
  with_ext    = add_ext(path)
  without_ext = rem_ext(path)

  if cache
    constant_name =
      without_ext
      .split(/[^a-zA-Z]/)
      .map(&:capitalize)
      .join
      .to_sym

    begin
      Object.const_get(constant_name)
    rescue NameError
      mod = gen_mod(with_ext)
      Object.const_set(constant_name, mod)
      mod
    end
  else
    gen_mod(with_ext)
  end
end

#require_module_relative(path, **options) ⇒ Object

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



54
55
56
57
58
59
60
61
# File 'lib/require_module.rb', line 54

def require_module_relative(path, **options)
  caller_filepath = caller_locations(1..1).first.absolute_path
  caller_dir = File.dirname(caller_filepath)

  fullpath = File.expand_path(path, caller_dir)

  require_module(fullpath, **options)
end