Ruby - Thor首先执行特定任务

时间:2020-12-31 02:19:57

Is it possible to call a specific task first, when i run a thor task?

当我运行Thor任务时,是否可以先调用特定任务?

my Thorfile:

class Db < Thor

  desc "show_Version", "some description ..."
  def show_version # <= needs a database connection
    puts ActiveRecord::Migrator.current_version
  end

  private

  def connect_to_database # <= call this always when a task from this file is executed
    # connect here to database
  end

end

I could write the "connect_to_database" method in every task but that seems not very DRY.

我可以在每个任务中编写“connect_to_database”方法,但这似乎不是很干。

2 个解决方案

#1


11  

You can use invoke to run other tasks:

您可以使用invoke来运行其他任务:

def show_version
  invoke :connect_to_database
  # ...
end

That will also make sure that they are run only once, otherwise you can just call the method as usual, e.g.

这也将确保它们只运行一次,否则你可以像往常一样调用方法,例如

def show_version
  connect_to_database
  # ...
end

Or you could add the call to the constructor, to have it run first in every invocation:

或者您可以将调用添加到构造函数中,以使其在每次调用中首先运行:

def initialize(*args)
  super
  connecto_to_database
end

The call to super is very important, without it Thor will have no idea what to do.

对super的调用非常重要,如果没有它,Thor将不知道该怎么做。

#2


1  

A rather under documented feature of thor is the method default_task. Passed a symbol from within your thor script, you can set it to run a specific task and, using invoke, run other thatks.

thor的一个相当不足的文档特征是方法default_task。从您的Thor脚本中传递了一个符号,您可以将其设置为运行特定任务,并使用调用运行其他任务。

ie:

default_task :connect_to_database;

#1


11  

You can use invoke to run other tasks:

您可以使用invoke来运行其他任务:

def show_version
  invoke :connect_to_database
  # ...
end

That will also make sure that they are run only once, otherwise you can just call the method as usual, e.g.

这也将确保它们只运行一次,否则你可以像往常一样调用方法,例如

def show_version
  connect_to_database
  # ...
end

Or you could add the call to the constructor, to have it run first in every invocation:

或者您可以将调用添加到构造函数中,以使其在每次调用中首先运行:

def initialize(*args)
  super
  connecto_to_database
end

The call to super is very important, without it Thor will have no idea what to do.

对super的调用非常重要,如果没有它,Thor将不知道该怎么做。

#2


1  

A rather under documented feature of thor is the method default_task. Passed a symbol from within your thor script, you can set it to run a specific task and, using invoke, run other thatks.

thor的一个相当不足的文档特征是方法default_task。从您的Thor脚本中传递了一个符号,您可以将其设置为运行特定任务,并使用调用运行其他任务。

ie:

default_task :connect_to_database;