Learning Outcome 7th May: require Vs require_relative

What comes into the minds of every programmer when you find the statement composed of ‘require’ or ‘require_relative’ mostly on the top of the codes or modules you are viewing. It is that obvious; include the mentioned module/package/class into the codes.

What do they do?

As a programmer, you don’t need to write a module of 1000 lines as if it is an all-in-one module that does pretty much everything you intend to accomplish. This is where require and require_relative comes into play to introduce dependencies of a module from either internal or external modules (in/out of the project/workspace). 

How do they differ?

require

require is mainly used to include dependencies (ex. Gems with ruby, classes, modules) that are external to the project or globally shared among projects.

Examples of global dependencies

  • Downloaded gems

  • Modules from other workspaces

  • etc.

require utilizes a global variable $LOAD_PATH which is an array of all paths to modules that can be imported to the requesting module and searches for a module/gem/class with the specified name, received as an argument.

  require (“file_name_as_argument”)

require_relative

Make use of the path of the requesting module to include the dependencies from other modules/classes relative to the requesting module.

require_relative (“. /folder_name/file_name_as_argument”)


Previous
Previous

How to setup secure subdomains using nginx and certbot on a digitalocean VPS

Next
Next

Learning Outcome 15th January 2020