Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass Hash as Parameter to Rake Task

I've got a rake task

task :post_hit, [:host, :title, :description, :model, :num_assignments, :reward, :lifetime, :qualifications, :p, :opts] => :environment do |t, args|

:p needs to be a hash, but if I try:

rake turkee:post_hit["http://www.staging.collegesportsbluebook.com","LS Info","Fill In Player First Name","MechanicalTurk",100,0.01,2,{},{id: 5},{}]

It errors out saying that id: could not be parsed (the space seemed to do something).

If I tried:

rake turkee:post_hit["http://www.staging.collegesportsbluebook.com","LS Info","Fill In Player First Name","MechanicalTurk",100,0.01,2,{},{"id: 5"},{}]

the who string "id: 5" was being interpreted as a single string.

Are we not allowed to pass hashes to rake tasks?

like image 516
Tyler DeWitt Avatar asked May 09 '12 20:05

Tyler DeWitt


People also ask

How do you call a rake task?

To run a rake task, just call the rake command with the name of your task. Don't forget to include your namespaces when you have them.

How do I create a rake task?

You can create these custom rake tasks with the bin/rails generate task command. If your need to interact with your application models, perform database queries and so on, your task should depend on the environment task, which will load your application code.

What is Rakefile?

A Rakefile contains executable Ruby code. Anything legal in a ruby script is allowed in a Rakefile. Now that we understand there is no special syntax in a Rakefile, there are some conventions that are used in a Rakefile that are a little unusual in a typical Ruby program.


1 Answers

I use querystring-like parameters and parse them with Rack::Utils.parse_nested_query

Here's how I do it

require 'rack/utils' # needed for Rack::Utils.parse_nested_query

namespace :foo do
  task :bar, [ :args_expr ] => :environment do |t, args|
     args.with_defaults(:args_expr => "name=abdo&fruits[]=bananas&fruits[]=dates")
     options = Rack::Utils.parse_nested_query(args[:args_expr])

     puts options
  end
end

And I call it like this: (notice how arrays and hashes are passed)

bundle exec rake "foo:bar[name=abdo&fruits[]=apples&fruits[]=oranges&hash[foo]=bar&hash[cool]=notmuch]"

Output:

{"name"=>"abdo", "fruits"=>["apples", "oranges"], "hash"=>{"foo"=>"bar", "cool"=>"notmuch"}}
like image 110
Abdo Avatar answered Sep 28 '22 08:09

Abdo