使用前/后钩子包装耙子任务 [英] Wrapping a rake task with a before/after hook

查看:39
本文介绍了使用前/后钩子包装耙子任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 rails 应用程序在 lib/tasks/*

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

当这些任务中的任何一个运行时,我想输出日志 STARTSTOP 消息.

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

这会运行一个带有参数 :some_arg 的 rake 任务,运行一个先决任务 (:some_pre_requisite),然后运行该任务.它在说我的任务已经开始和停止之前和之后输出日志语句.

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

  • 打印START 语句
  • 调用/产生/运行名为
  • 的实际rake任务
  • 打印STOP 语句
  • prints the START statement
  • invokes/yields/runs the actual rake task called
  • prints the STOP statement

我知道我可以将第一次打印设置为先决条件,然后将第二次打印设置为单独的增强任务,但这感觉很混乱.它将两个打印语句存储在不同的位置,而且我必须单独手动enhance每个任务.

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?

谢谢!

推荐答案

关于 after 钩子:

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'])

这篇关于使用前/后钩子包装耙子任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆