Skip to content

Instantly share code, notes, and snippets.

@candland
Forked from latentflip/Rakefile
Last active June 23, 2021 15:57
Show Gist options
  • Select an option

  • Save candland/6194967 to your computer and use it in GitHub Desktop.

Select an option

Save candland/6194967 to your computer and use it in GitHub Desktop.

If you have rake tasks that don't rely on rails, it's really annoying that rails has to load before the tasks runs.

Instead this rakefile only loads rails if a rake task which depends on :environment is called.

  • Added a call to Rake::Application#clear before loading the rails environment so that tasks are not called twice, and so that tasks can be called again.

One caveat is that rake -T won't list rails/gem tasks, hence the added warning. To show all tasks use rake -T LOAD_RAILS=1

With thanks to @xshay http://rhnh.net/2010/09/07/speeding-up-rails-rake

Any thoughts?

#!/usr/bin/env rake
# Add your own tasks in files placed in lib/tasks ending in .rake,
# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake.
#The original rails rakefile loading
def load_rails_environment
require File.expand_path('../config/application', __FILE__)
require 'rake'
MyApp::Application.load_tasks
end
#Catch task missing and try again
class Rake::Application
private
alias_method :invoke_task_without_catch, :invoke_task
def invoke_task_with_catch(*args)
begin
puts "Trying #{task_string}"
invoke_task_without_catch(*args)
rescue RuntimeError => e
if m = /task '([^']*)'/i.match(e.message)
puts "Loading Rails for: #{m[1]}"
self.clear()
load_rails_environment
invoke_task_without_catch(task_string)
end
end
end
alias_method :invoke_task, :invoke_task_with_catch
end
#Add a task to the top of the rake -T list, to explain how to get the full list
#of tasks including rails and gem tasks
if ENV['LOAD_RAILS'] == '1'
load_rails_environment
else
#Load all the tasks in lib/tasks
Dir[File.expand_path('../lib/tasks/', __FILE__) + '/*.rake'].each do |file|
load file
end
desc "!!! Rails and gem tasks are not listed, rerun with LOAD_RAILS=1 to reveal"
task :_README
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment