加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Ruby – Thor首先执行特定任务

发布时间:2020-12-17 04:14:46 所属栏目:百科 来源:网络整理
导读:当我运行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_dat
当我运行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将不知道该怎么做.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读