Ruby – 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

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

解决方法

您可以使用invoke来运行其他任务:
def show_version
  invoke :connect_to_database
  # ...
end

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

def show_version
  connect_to_database
  # ...
end

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

def initialize(*args)
  super
  connecto_to_database
end

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

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...