Ruby - Thor首先执行特定任务

ips*_*sum 7 ruby initialization task thor

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

我的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
Run Code Online (Sandbox Code Playgroud)

我可以在每个任务中编写"connect_to_database"方法,但这看起来不是很干.

The*_*heo 12

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

def show_version
  invoke :connect_to_database
  # ...
end
Run Code Online (Sandbox Code Playgroud)

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

def show_version
  connect_to_database
  # ...
end
Run Code Online (Sandbox Code Playgroud)

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

def initialize(*args)
  super
  connecto_to_database
end
Run Code Online (Sandbox Code Playgroud)

打电话super是非常重要的,没有它,Thor将不知道该怎么做.

  • 尝试添加一个构造函数:`definitialize(*args); 极好的; 连接到数据库;结束` (2认同)