Rake Task: invoke or execute??
What is Rake? Why we need it?
Rake is Ruby Make, a standalone Ruby utility that replaces the Unix utility ‘make’, and uses a ‘Rakefile’ and .rake files to build up a list of tasks.
Putting in a simple word :
rake will execute different tasks(basically a set of ruby code) specified in any file with .rake extension from the command line.
In Rails, a rake is a gem in itself and installation dependency of rails i.e. whenever you install rails rake gem get installed along with it.
Creating Rake Task
First let`s see what is Namespaces:
To organize your code better, rake supports the concept of namespaces. This essentially lets you group tasks inside a single namespace.
namespace :universe do
namespace :world do
#…
end
end
Now let`s create a simple rake task to display “hello world” message.
The description (desc) is useful because it gets displayed when you list all available tasks.
namespace :universe do
namespace :world do
desc 'shout message'
task :shout do
puts "hello world"
end
end
end
How to run rake?
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.
Namespaces and tasks are separated using a colon(:)
$ rake universe:world:shouthello world
Running Rake from console:
Running your Rake tasks requires two steps:
- Loading Rake
- Loading your Rake tasks
require 'rake'
MyRailsApp::Application.load_tasks
- Without parameter
Rake::Task['universe:world:shout'].invoke
Rake::Task['universe:world:shout'].execute
2. With parameter
- With Argument as hash
task :activate_account, :account_id do |t, args|
account_id = args[:account_id] # ACCESSING args AS HASH
account = Account.find_by(id: account_id)
account.update_column(state: "Active")
end# using invoke - IT WILL RUN ONLY ONCE
Rake::Task['activate_account'].invoke([111])# using execute
Rake::Task['activate_account'].execute({account_id: 111})
- With Argument as Method call
task :activate_account, :account_id do |t, args|
account_id = args.account_id # ACCESSING args AS METHOD CALL
account = Account.find_by(id: account_id)
account.update_column(state: "Active")
end#using invoke # IT WILL RUN ONLY ONCE
Rake::Task['activate_account'].invoke([111])#using execute
Rake::Task['activate_account'].execute(Rake::TaskArguments.new([:account_id], [1111]))
Difference between invoke & execute:
Difference between invoke and execute is the execution of your dependencies.
- execute: your task will get executed, but not the dependency
- invoke: will call the whole chain.
References: