Wrapping a rake task with a before/after hook

2019-02-25 13:20发布

My rails app has several custom rake tasks defined under lib/tasks/*

When any of these tasks run, I'd like to output a log START and STOP message.

For an individual rake task, I can do something like

namespace :foo do
  task :bar, [:some_arg] => :some_pre_requisite do |t, args|
    Rails.logger.info "Rake START - {task: \"#{t}\", args: #{args}}"

    # Do stuff

    Rails.logger.info "Rake STOP - {task: \"#{t}\", args: #{args}}"
  end
end

This runs a rake task that takes an argument :some_arg, runs a pre-requisite task (:some_pre_requisite) and then runs the task. It outputs log statements before and after saying that my task has started and stopped.

If I have several dozen tasks, this gets really repetitive. I'd love to "wrap" the rake task in some other method that

  • prints the START statement
  • invokes/yields/runs the actual rake task called
  • prints the STOP statement

I know I could set up the first print as a pre requisite and then the second print as a separate enhanced task, but that feels messy. It stores both print statements in different locations, and plus I'd have to manually enhance each task individually.

Any better thoughts on how this could be acheived?

Thanks!

1条回答
混吃等死
2楼-- · 2019-02-25 14:15

About the after hook:

Rake::Task['db:migrate'].enhance do
  puts "AFTER"
end

http://ruby-doc.org/stdlib-2.0.0/libdoc/rake/rdoc/Rake/Task.html#method-i-enhance

For the before hook (untested):

task :before do
  puts "BEFORE"
end

Rake::Task['db:migrate'].enhance(['before'])
查看更多
登录 后发表回答