How to pass command line arguments to a rake task
Options and dependencies need to be inside arrays:
namespace :thing do
desc "it does a thing"
task :work, [:option, :foo, :bar] do |task, args|
puts "work", args
end
task :another, [:option, :foo, :bar] do |task, args|
puts "another #{args}"
Rake::Task["thing:work"].invoke(args[:option], args[:foo], args[:bar])
# or splat the args
# Rake::Task["thing:work"].invoke(*args)
end
end
Then
rake thing:work[1,2,3]
=> work: {:option=>"1", :foo=>"2", :bar=>"3"}
rake thing:another[1,2,3]
=> another {:option=>"1", :foo=>"2", :bar=>"3"}
=> work: {:option=>"1", :foo=>"2", :bar=>"3"}
NOTE: variable
task
is the task object, not very helpful unless you know/care about Rake internals.
RAILS NOTE:
If running the task from Rails, it's best to preload the environment by adding
=> [:environment]
which is a way to setup dependent tasks.
task :work, [:option, :foo, :bar] => [:environment] do |task, args|
puts "work", args
end
Passing arguments to a method in Rake Task
You have access to the parameter like a hash-parameter (1):
task :daily_sales_commission, [:arg1, :arg2] do |t,args|
#args can be treated like a hash.
get_date(args[:arg1], args[:arg2]) #<- call your method
end
def get_date(arg1,arg2)
#some code
end
These parameters are not common command line parameters, you must use them directly as parameters of the rake parameter. The example takes 1 and 2 as parameter values:
rake daily_sales_commission[1,2]
(1) It is not a Hash, it is a Rake::TaskArguments-object. But you can also use the []
to access the parameters.
How to pass arguments into a Rake task with environment in Rails?
TLDR;
task :t, [args] => [deps]
Original Answer
When you pass in arguments to rake tasks, you can require the environment using the :needs option. For example:
desc "Testing environment and variables"
task :hello, :message, :needs => :environment do |t, args|
args.with_defaults(:message => "Thanks for logging on")
puts "Hello #{User.first.name}. #{args.message}"
end
Updated per @Peiniau's comment below
As for Rails > 3.1
task :t, arg, :needs => [deps] # deprecated
Please use
task :t, [args] => [deps]
passing argument to rake task in Ruby on Rails
I'm not so sure, but I guess you should be able to do:
if Rails.env.development? or Rails.env.test?
namespace :clear_data do
desc 'clear time slots'
task :clear_time_slots, [:post_id] => :environment do |_, args|
TimeSlot.where('health_post_id > ?', args[:post_id]).destroy_all
end
desc "Clean the Practices table"
task :clear_practice_records, [:post_id] => :environment do |_, args|
Practice.where('health_post_id > ?', args[:post_id]).destroy_all
end
desc "clean database"
task :clear_database, [:post_id] => :environment do |_, args|
max = args[:post_id]
Rake::Task['clear_data:clear_practice_records'].execute(post_id: max)
Rake::Task['clear_data:clear_time_slots'].execute(post_id: max)
#OR
#Rake::Task['clear_data:clear_practice_records'].invoke(max)
#Rake::Task['clear_data:clear_time_slots'].invoke(max)
end
end
end
RAILS - Passing parameters to a Rake task
[:arg1]
must be args[:arg1]
(or whatever name you use as block argument). Here's the code:
task :export, [:arg1] => :environment do |t, args|
puts "Exporting..."
Importer.export_to_csv(args[:arg1])
puts "done."
end
Usage:
rake export[foo1]
Passing a parameter or two to a Rake task
The way rake commands accept and define arguments is, well, not pretty.
Call your task this way:
<prompt> rake db:do_something[1,2]
I've added a second parameter to show that you'll need the comma, but omit any spaces.
And define it like this:
task :do_something, :arg1, :arg2 do |t, args|
args.with_defaults(:arg1 => "default_arg1_value", :arg2 => "default_arg2_value")
# args[:arg1] and args[:arg2] contain the arg values, subject to the defaults
end
How can I pass named arguments to a Rake task?
You can say things like this:
rake some_task -- --arg=value
And then, inside your task, ARGV
will be
[ 'some_task', '--arg=value' ]
so you could use OptionParser (or some other option parser) to unpack ARGV
just like in any old CLI script; the funny looking --
is necessary to keep rake from trying to parse --arg=like
as a rake switch.
You're probably better off with the standard environment variable approach, it isn't as ugly as all the --
stuff and it is the usual way of passing arguments to rake tasks.
Logic to test whether a command line argument to a rails rake task is present?
An argument provided to a rake task via var=value
is accessible inside the rake task with ENV['var']
.
If the argument is not provided, ENV['var']
will return nil
.
So you can simply check ENV['email'].nil?
i.e.
if ENV['email'].nil?
puts "Please provide an email"
else
# code to run if email is provided
end
Related Topics
How to Remove Rvm (Ruby Version Manager) from My System
Code Block Passed to Each Works With Brackets But Not With 'Do'-'End' (Ruby)
Begin, Rescue and Ensure in Ruby
What Are the Ruby Gotchas a Newbie Should Be Warned About
Understanding [Classone, Classtwo].Each(&:My_Method)
Sort Hash by Key, Return Hash in Ruby
Aws S3: the Bucket You Are Attempting to Access Must Be Addressed Using the Specified Endpoint
Why Is This Rmagick Call Generating a Segmentation Fault
Error When Running Rails App - Execjs::Runtimeerror
Understanding the Rails Authenticity Token
How to Sum Array of Numbers in Ruby
How to "Pretty" Format Json Output in Ruby on Rails
How to Install Postgresql'S Pg Gem on Ubuntu
Ruby: Inherit Code That Works With Class Variables
Block Definition - Difference Between Braces and Do-End