'How to access Rails model in a rake file outside of rake tasks?

In order to access Rails models in a rake task you give :environment as a dependency. But what if you want to have dynamic descriptions of your task and they depend on some database date. For example:

end_date = Foo.end_date # the model foo provides some end date

desc "Do something after #{end_date}"
task bar: :environment do
  ...
end

I tried Rake::Task[:environment].invoke, but I get Don't know how to build task 'environment'.



Solution 1:[1]

I've just discovered that you can load up the rails environment a bit more manually. I just stick this at the top of the file containing the rake task:

# Pre-load the rails environment so we can dynamically create 
# these tasks. Your path may vary.

require File.expand_path('../../../config/environment', __FILE__)

# Eager load the models so I have access to them, this may be 
# different in your environment.

Zeitwerk::Loader.eager_load_all

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 counterbeing