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 callingKernel#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 returnsfalse
. Afterrequire
the file, the path of the file would be appended to the global variable$LOADED_FEATURES
cat tmp.rb
#=> $COUNT ||= 0
#=> $COUNT += 1
#=> p $COUNTload '/home/ubuntu/tmp.rb'
#=> 1
#=> trueload '/home/ubuntu/tmp.rb'
#=> 2
#=> truerequire '/home/ubuntu/tmp.rb'
#=> 3
#=> truerequire '/home/ubuntu/tmp.rb'
#=> false
- The
Kernel#autoload
is used for loading lazilyConstance
(usingKernel::require
). Only loadConstance
when theConstance
is called.
cat tmp.rb
#=> class A; p 'load class A' endautoload :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
#=> Aautoload? :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