Thursday, December 22, 2011

Ruby Require vs Load


The load and require methods are use to include additional source files, these both methods you need to be used only if library you are loading is defined in a separate file.

These both methods defined under 'Kernel' module of ruby.

The require method allows you to load a library and prevents it from being loaded more than once. The require method will return ‘false’ if you try to load the same library after the first time.
So it keeps track of whether that library was already loaded or not. You also don’t need to specify the “.rb” extension of the library file name.

Here is the code from 'boot.rb'
require 'rubygems'

# Set up gems listed in the Gemfile.
ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__)

require 'bundler/setup' if File.exists?(ENV['BUNDLE_GEMFILE'])


Load
The load method is almost same like require method but it doesn’t keep track of whether specified library has been loaded or not. It should be used only if each time we want to load specific library and module changes done frequently. Here we need to specify the file extension.
load(File.dirname(__FILE__) + "/schema.rb")