The rake eager loading feature was disabled in Rails in 2013 due to an issue with precompilation. The pull request to enable eager loading in rake tasks was finally merged and is scheduled to be released in Rails.
Let’s first understand what happens when eager_load
is set to true in rails config. As stated in the Rails Edge Guides:
config.eager_load
whentrue
, eager loads all registeredconfig.eager_load_namespaces
. This includes your application, engines, Rails frameworks, and any other registered namespace.
Similarly, when config.rake_eager_load
is set as true all registered namespaces are loaded when we run the rake task.
Let’s look at an example to understand how this works.
class Test
TIMER = Time.current.strftime("%H:%M:%S")
end
We create a Test
class with a constant TIMER
which will have the class initialization time.
task test_rake_eager_config: :environment do
puts "Rails.application.config.eager_load: #{Rails.application.config.eager_load}"
puts "Rails.application.config.rake_eager_load: #{Rails.application.config.rake_eager_load}"
puts "Time: #{Time.current.strftime("%H:%M:%S")}"
sleep(1)
puts "Time: #{Time.current.strftime("%H:%M:%S")}"
sleep(1)
puts "Time: #{Time.current.strftime("%H:%M:%S")}"
sleep(1)
puts "Time in Test class : #{Test::TIMER}"
end
We also set up a rake task test_rake_eager_config
to test the rake_eager_load
config.
Lets start by keeping the config.rake_eager_load
as false
.
Rails.application.config.eager_load: false
Rails.application.config.rake_eager_load: false
Time: 10:34:09
Time: 10:34:10
Time: 10:34:11
Time in Test class : 10:34:12
When the rake_eager_load
is set as false the configurations are not loaded as all the registered namespaces are not loaded. Hence the config.eager_load
will appear as false
even if we set it as true
.
If we observe the Time, the TIMER
constant in the Test
class is loaded only when its invoked.
Hence the first output for Time is lesser than the Test
class invocation but when config.rake_eager_load
is set as true
.
Rails.application.config.eager_load: true
Rails.application.config.rake_eager_load: true
Time: 10:34:36
Time: 10:34:37
Time: 10:34:38
Time in Test class : 10:34:35
All the configurations in the environment config files are loaded.
Hence the actual values are reflected.
Besides, if we observe the Time
,
the initial Time
and the final are the same, as the Test
class in eager loaded for the rake task.