如何多次调用Thor任务?

时间:2012-10-05 15:19:38

标签: ruby rake thor

Thor喜欢Rake(和Make)有任务管理。如果我多次调用一个任务,它只会有效地调用一次任务。如何多次调用任务?

我尝试修改@_invocations哈希,但这不起作用:

require 'csv'
require './config/environment'

class MisReport < Thor

  desc "all", "generate mysql and postgres mis"
  def all
    generate("pg_mis_report", "pg")
    generate("mysql_mis_report", "mysql") 
  end

  desc "generate", "generate mis report"
  def generate(file_name = "mis_report_#{Time.now.to_s(:number)}", connection = "postgres") 
    if connection == "pg"
      puts "== postgres database"
      ActiveRecord::Base.establish_connection :development_mysql
    else
      puts "== mysql database"
      ActiveRecord::Base.establish_connection :development
    end

    # generate MIS

    puts
    puts "mis file is at: #{file_path}"
  end

end

2 个答案:

答案 0 :(得分:2)

class MisReport < Thor

  desc "all", "generate mysql and postgres mis"
  def all
    MisReport.new.invoke "generate", ["pg_mis_report", "pg"]
    MisReport.new.invoke "generate", ["mysql_mis_report", "mysql"]
  end
end

它支持使用选项调用。

答案 1 :(得分:0)

通过Thor文档,我无法找到一种强制多次调用相同任务的方法。这可能是设计上的。

我已经创建了一个解决方法,通过将报告生成请求组合到单个任务中来执行您所要求的工作,而该任务又依赖于“非任务”块,Thor可用于非任务方法。您可以灵活地添加要生成的新报告,方法是将它们添加到传递给generate的哈希参数中。

class MisReport < Thor

  desc "all", "generate mysql and postgres mis"
  def all
    generate({:pg_mis_report => "pg", :mysql_mis_report => "mysql"})
  end

  desc "generate", "generate mis report"
  def generate(hash)
    hash.each_pair {|file_name, connection| generate_report(file_name.to_s, connection)}
  end

  no_tasks{
    def generate_report(file_name = "mis_report_#{Time.now.to_s(:number)}", connection = "postgres") 

      if connection == "pg"
        puts "== postgres database"
        #ActiveRecord::Base.establish_connection :development_mysql
      else
        puts "== mysql database"
        #ActiveRecord::Base.establish_connection :development
      end

      # generate MIS

      file_path = "/some/path/to/#{file_name}"
      puts
      puts "mis file is at: #{file_path}"
    end
  }

end

我已经测试了它,输出显示在这里:

$> thor mis_report:all
== postgres database

mis file is at: /some/path/to/pg_mis_report
== mysql database

mis file is at: /some/path/to/mysql_mis_report

希望这有帮助。