Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically requiring files?

Tags:

Does anyone know enough about Ruby's require to tell me if the following is valid syntax:

class Something

  def initialize(mode)
     case mode
     when :one then require 'some_gem'
     when :two then require 'other_gem'
     end
  end

end

s = Something.new

If so, will the require place the gem into the global namespace as it would when at the top of the file?

like image 872
Roja Buck Avatar asked Feb 09 '10 16:02

Roja Buck


People also ask

What is await import?

When the import keyword is used as a function: const module = await import(path); It returns a promise and starts an asynchronous task to load the module. If the module was loaded successfully, then the promise resolves to the module content, otherwise, the promise rejects.

What is require () in JavaScript?

1) require() In NodeJS, require() is a built-in function to include external modules that exist in separate files. require() statement basically reads a JavaScript file, executes it, and then proceeds to return the export object.

What is dynamic import in JavaScript?

Dynamic imports or Code Splitting is the practice of breaking up your JavaScript modules into smaller bundles and loading them dynamically at runtime to improve and increase the performance of your website dramatically.


2 Answers

If so, would the require place the gem into the global namespace as the same require at the top of the file would?

Yes. require doesn't have scope, while load does.

like image 186
Simone Carletti Avatar answered Nov 04 '22 11:11

Simone Carletti


Yes it's perfectly valid and works as expected because require isn't scoped

Require pulls in the code from the specified file and attempts to use it in-place - that might mean that it isn't sensible to do but yes it can be done.

The local method scope would be unaffected and any class definition etc would be at the expected scope

like image 40
Chris McCauley Avatar answered Nov 04 '22 12:11

Chris McCauley