Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pass an array as an argument to a Rake task?

Tags:

ruby

rake

I'm writing a Rake task and I want to pass an array as one of the arguments. Here's how I currently have it.

task :change_statuses, :ids, :current_status, :new_status do |task, args|   puts "args were #{args.inspect}" end 

I've tried running the task these ways:

# First argument as array rake "change_statuses[[1,2,3], active, inactive]"  # First argument as string rake "utility:change_account_statuses['1,2,3', foo, bar]" 

My expected output would be:

args were {:ids=> [1,2,3], :current_status=> 2 , :new_status=> 3} 

However, my actual output in each case is:

args were {:ids=>"[1", :current_status=>"2", :new_status=>"3]"} 

How can I pass an array to a Rake task?

like image 452
Nathan Long Avatar asked Aug 21 '12 13:08

Nathan Long


People also ask

How do I list a rake task?

You can get a list of Rake tasks available to you, which will often depend on your current directory, by typing rake --tasks . Each task has a description, and should help you find the thing you need.

What is environment rake task?

Including => :environment will tell Rake to load full the application environment, giving the relevant task access to things like classes, helpers, etc. Without the :environment , you won't have access to any of those extras.


2 Answers

One of the soulutions is to avoid , symbol in the string, so your command line would look like:

$ rake change_statuses['1 2 3', foo, bar] 

Then you can simply split the IDs:

# Rakefile  task :change_statuses, :ids, :current_status, :new_status do |task, args|   ids = args[:ids].split ' '    puts "args were #{args.inspect}"   puts "ids were #{ids.inspect}" end 

Or you can parse the ids value to get your expected output:

args[:ids] = args[:ids].split(' ').map{ |s| s.to_i } 

I'm using rake 0.8.7

like image 96
lks128 Avatar answered Sep 20 '22 09:09

lks128


Another way to achieve this and also win the ability to pass a hash

namespace :stackoverflow do   desc 'How to pass an array and also a hash at the same time 8-D'   task :awesome_task, [:attributes] do |_task, args|     options = Rack::Utils.parse_nested_query(args[:attributes])     puts options   end end 

And just call the rake task like this:

bundle exec rake "stackoverflow:awesome_task[what_a_great_key[]=I know&what_a_great_key[]=Me too\!&i_am_a_hash[and_i_am_your_key]=what_an_idiot]" 

And that will print

{"what_a_great_key"=>["I know", "Me too!"], "i_am_a_hash"=>{"and_i_am_your_key"=>"what_an_idiot"}} 
like image 27
MatayoshiMariano Avatar answered Sep 19 '22 09:09

MatayoshiMariano