我已将 my_checks
方法调用附加到 Rails db:migrate
调用。只要 db:migrate
不抛出异常,下面的代码就可以很好地工作。但是,如果 db:migrate
确实抛出异常,则不会执行 my_checks
方法。
有没有一种方法可以重写下面的代码,以确保无论 db:migrate
中发生什么,my_checks
都得到执行?
namespace :db do
def my_checks
...
end
task :migrate do
my_checks
end
end
最佳答案
只需将其包装在 begin/rescue/ensure/end
语句中即可:
namespace :db do
def my_checks
...
end
task :migrate do
begin
# something that may raise error
rescue
# what to do if error, you can omit this if you don't care about error
ensure
my_checks
end
end
end
编辑
我会这样做:
namespace :db do
def my_checks
...
end
task :my_migrate do
begin
Rake::Task['db:migrate'].invoke
rescue
# what to do if error, you can omit this if you don't care about error
ensure
my_checks
end
end
end
编辑 2
好的,试试:
def alias_task(name, old_name)
# from https://gist.github.com/raggi/232966
t = Rake::Task[old_name]
desc t.full_comment if t.full_comment
task name, *t.arg_names do |_, args|
# values_at is broken on Rake::TaskArguments
args = t.arg_names.map { |a| args[a] }
t.invoke(args)
end
end
alias_task 'db:old_migrate', 'db:migrate'
namespace :db do
def my_checks
puts 'ok'
end
task :migrate do
begin
Rake::Task["db:old_migrate"].execute
ensure
my_checks
end
end
end
编辑 3
好的,这应该可行,而且简单得多:
namespace :db do
def my_checks
puts 'ok'
end
task :other do
at_exit { my_checks }
end
end
Rake::Task['db:migrate'].enhance(['db:other'])
根据已故 Jim Weirich 在 https://www.ruby-forum.com/topic/61010 的建议使用 at_exit
.
参见 http://ruby-doc.org/stdlib-1.9.3/libdoc/rake/rdoc/Rake/Task.html有关增强
的更多信息。
关于ruby - 确保 Rake 任务的附加代码无论如何都能运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24369468/