load, require and autoload files in Ruby

dieutb
2 min readJun 3, 2021

--

As usual, Kernel#load, Kernel#require help to load and execute code in a file

  • The Kernel#load takes the relative/absolute file path as a parameter. The file could be executed many times corresponding with the number of times calling Kernel#load. If the purpose is always to reload the code without restarting the server, Kernel#load is a good choice
  • The Kernel#require takes the absolute file path as a parameter. If not found, Ruby would look for the file in the directories listed in $LOAD_PATH. Only load and execute code/file one time. From the second time, instead of loading and executing the code in the file, it returns false. After require the file, the path of the file would be appended to the global variable $LOADED_FEATURES
cat tmp.rb
#=> $COUNT ||= 0
#=> $COUNT += 1
#=> p $COUNT
load '/home/ubuntu/tmp.rb'
#=> 1
#=> true
load '/home/ubuntu/tmp.rb'
#=> 2
#=> true
require '/home/ubuntu/tmp.rb'
#=> 3
#=> true
require '/home/ubuntu/tmp.rb'
#=> false
  • The Kernel#autoload is used for loading lazily Constance (using Kernel::require). Only load Constance when the Constance is called.
cat tmp.rb
#=> class A; p 'load class A' end
autoload :A, '/home/ubuntu/tmp.rb'
#=> nil
autoload? :A # if A is just in register not loaded yet, it would return a path of file
#=> '/home/ubuntu/tmp.rb'
A
#=> load class A
#=> A
autoload? :A # A was loaded, then autoload? return nil
#=> nil

Directory

  • List all dirs/files in current dir Dir.glob('*')
  • Get current absolute path of dir Dir.pwd
  • copy directory and all file inside FileUtils.cp_r('data', 'backup')

File

  • relative-path File.dirname(__FILE__)
  • absolute-path File.absolute_path(File.dirname(__FILE__))
  • join paths File.join(File.dirname(__FILE__), '../', 'public/tmp.rb')
  • check file exists File.file?(‘path-to-file’)
  • more options

References

--

--

dieutb
dieutb

Written by dieutb

passion in finding solutions and research some things relate to technical and helpful in life. Also strongly interest in foods, travel, and gentle music :)

No responses yet