Skip to content

Instantly share code, notes, and snippets.

@seancdavis
Last active August 16, 2022 07:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save seancdavis/8cdf96c8590f49f8a1dd to your computer and use it in GitHub Desktop.
Save seancdavis/8cdf96c8590f49f8a1dd to your computer and use it in GitHub Desktop.
Automatically load rake tasks within namespaces based on directory structure within `lib/tasks` directory.
# lib/tasks/load_tasks.rake
# ------------
# Looks at every .rb file in the lib/tasks and adds them to rake within the
# namespace of their subdirectories
# ------------
# Important to note we are looking specifically for .rb files, so they
# aren't added to the global rake namespace
Dir.glob("#{Rails.root}/lib/tasks/**/*.rb").each do |file|
path = file.split('/')
namespaces = path[(path.index('tasks') + 1)..-2]
filename = path.last
if namespaces.size > 0
namespace namespaces[0].to_sym do
if namespaces.size > 1
while namespaces.size > 1
namespaces = namespaces[1..-1]
namespace namespaces[0].to_sym do
load file if namespaces.size > 0
end
end
else
load file
end
end
else
load file
end
end
# lib/tasks/dir_1/dir_2/create_files.rb
# ------------
# Tasks here are loaded into the dir_1:dir_2 namespace because it is inside
# the dir_1/dir_2 subdirectory
# ------------
desc "My exampled namespaced task"
task :xtask => :environment do
# task can be executed with `bundle exec rake dir_1:dir_2:xtask`
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment