Rake Execute With Multiple Arguments

2019-07-20 08:00发布

问题:

I'm calling a rake task within a task and I'm running into a roadblock when it comes to calling execute

response = Rake::Task["stuff:sample"].execute[:match => "HELLO"]

or

response = Rake::Task["stuff:sample"].execute[:match => "HELLO",:freq=>'100']

Calling task

task :sample, [:match,:freq] => :environment  do |t, args|

The error I get back is 'can't convert Hash into Integer'

Any ideas?

回答1:

I think the problem is in code you're not posting. Works fine for me:

james@James-Moores-iMac:/tmp$ head r.rb call.rb 
==> r.rb <==
task :sample, [:match,:freq] do |t, args|
  puts "hello world"
  puts args[:match]
end

==> call.rb <==
require 'rubygems'
require 'rake'
load 'r.rb'
Rake::Task["sample"].execute :match => "HELLO"
james@James-Moores-iMac:/tmp$ ruby call.rb 
hello world
HELLO
james@James-Moores-iMac:/tmp$ 


回答2:

The square brackets in your execute syntax confuse me. Is that a special rake syntax (that you may be using incorrectly) or do you mean to send an array with one element (a hash)? Isn't it the same as this?

response = Rake::Task["sample"].execute([:match => "HELLO",:freq=>'100'])

Beyond that, Task#execute expects Rake:TaskArguments.

class TaskArguments
    ...

    # Create a TaskArgument object with a list of named arguments
    # (given by :names) and a set of associated values (given by
    # :values).  :parent is the parent argument object.
    def initialize(names, values, parent=nil)

You could use:

stuff_args = {:match => "HELLO", :freq => '100' }
Rake::Task["stuff:sample"].execute(Rake::TaskArguments.new(stuff_args.keys, stuff_args.values))

You could also use Task#invoke, which will receive basic args. Make sure you Task#reenable if you invoke it multiple times.