Mastodon

Rake tasks with arguments

After a little digging and a little time to RTFM, I finally have a working rake task with arguments. The interesting thing about it is that Rake will not pass arguments to a task that is not expecting them. “Expecting them” takes the form of actually passing them as an argument to the task method right after the name. If you want to have defaults you will have to call with_defaults on the incoming args hash. Its a little weird but that’s how it works.

namespace :mike do
  desc "Playing with Rake arguments"
  task :test, [:arg1, :arg2] do |task, args|
    args.with_defaults(arg1: "foo", arg2: "bar")
    puts args.inspect
  end
end

That task can be invoked from code like this:

Rake::Task["mike:test"].invoke("Fizz", "Buzz")

Unfortunately the space between the arguments means that running it from the command line requires quotes:

rake "mike:test[Fizz, Buzz]"

As nice as it is to have figured this out, I think the real question at this point is “Why am I not making this thing a class in my application?”, which of course I should be…

Ahh well, at least this will be here for some future project when I have a convincing answer to that.

Leave a Reply

Discover more from mikewilliamson.dev

Subscribe now to keep reading and get access to the full archive.

Continue reading