Ruby – Thor首先执行特定任务

前端之家收集整理的这篇文章主要介绍了Ruby – Thor首先执行特定任务前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
当我运行Thor任务时,是否可以先调用特定任务?

我的Thorfile:

  1. class Db < Thor
  2.  
  3. desc "show_Version","some description ..."
  4. def show_version # <= needs a database connection
  5. puts ActiveRecord::Migrator.current_version
  6. end
  7.  
  8. private
  9.  
  10. def connect_to_database # <= call this always when a task from this file is executed
  11. # connect here to database
  12. end
  13.  
  14. end

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

解决方法

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

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

  1. def show_version
  2. connect_to_database
  3. # ...
  4. end

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

  1. def initialize(*args)
  2. super
  3. connecto_to_database
  4. end

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

猜你在找的Ruby相关文章