Today I Learned

hashrocket A Hashrocket project

Rails Environment Task

In a Rails task if you need to load in your rails application (to get access to your models, etc.), you have to call :environment in the task:

task task_name: :environment do 
  ...
end

I kind of always took this for granted, and never thought much about it. Then, in Xavier Noria's 2024 Rails World talk he mentioned that :environment itself is a task - and that syntax is actually saying your task depends upon :environment and run that task before your task runs. 🤯

So I decided to look up what the environment task actually does:

task :environment do
  ActiveSupport.on_load(:before_initialize) { config.eager_load = config.rake_eager_load }

  require_environment!
end

require_environment! ... requires your environment, specifically it requires your config/environment.rb which runs Rails.application.initialize! - which is what actually starts your rails app.

Cool!

See More #rails TILs
Looking for help? Hashrocket has been an industry leader in Ruby on Rails since 2008. Rails is a core skill for each developer at Hashrocket, and we'd love to take a look at your project. Contact us and find out how we can help you.