[Rails] auto-load, reload, load, require, include, extend

Tags
Rails
Engineering
Created
Oct 21, 2023 12:05 AM
Edited
Oct 20, 2023
Description
auto-load, reload, load, require, include, extend
đź’ˇ
Rule of thumbs to use load and require: firstly check if your file is loaded automatically. Secondly, check if your file is static and won’t be changed so only needed to be loaded once, then use require. Finally, use load if the file is dynamically and frequently changed.

auto-load

Rails automatically reloads classes and modules if application files in the autoload paths change.
More precisely, if the web server is running and application files have been modified, Rails unloads all autoloaded constants managed by the main autoloader just before the next request is processed.

What can be auto-loaded?

  • Everything under app
  • Or, further extend config.autoload_paths, in config/application.rb or config/environments/*.r
# extend config.autoload_paths, in config/application.rb 
# or config/environments/*.r
module MyApplication
  class Application < Rails::Application
    config.autoload_paths << "#{root}/extras"
  end
end

reload

Mostly used in Rails console, because it does not auto-load files in Rails console
User.object_id
reload!
User.object_id

load

  • Explicitly load everything from a file in another file
  • Rarely used when a file is frequently dynamically changed, because most files are auto-loaded or we prefer require
load "file name"

require

  • Similar to load but only load the file once and save it to memory for every later use
require "filename"

include

  • include is used to import module code with “object access”
module Geek
  def geeks
    puts 'GeeksforGeeks!'
  end
end
   
class Lord
  # only can access geek methods
  # with the instance of the class.
  include Geek
end

# object access 
Lord.new.geeks

# NoMethodError: undefined  method
# `geeks' for Lord:Class
Lord.geeks

extend

  • Extend is also used to import module code with “class access”r
module Geek
  def geeks
    puts 'GeeksforGeeks!'
  end
end
   
class Star
  # only can access geek methods
  # with the class definition.
  extend Geek
end
  
# class access
Star.geeks

Source