Add parameters to your Rails tasks

I think adding parameters to Rake task is usually necessary. What is rake? It’s a ruby utility that you can use to build up a list of tasks, for your project, in a dynamic way. In order to create a rake task, you can just run

rails g task your_tasks_domain your_first_task your_second_task

Or, you can, create in a manual way, by adding a .rake file in lib/tasks folder

# lib/tasks/your_task_domain.rake
namespace :your_tasks_domain do
  desc "TODO"
  task your_first_task: :environment do
  	# You will write your code here
  	# For example: Task.create(name: "my first task")
  end
  desc "TODO"
  task your_second_task: :environment do
  end
end


How to use it? Normally we execute below command in your shell

rake your_tasks_domain:your_first_task

A common use case is I wanna add parameters to my rake tasks? How to do and how to use it?

  1. How to add arguments to rake task
    You can use below code

    namespace :your_domain do
      desc "TODO: your task description"
      task :your_task, [:your_argument_1, :your_argument_2] => :environment do |_, args|
        if args.your_argument_1 == args.your_argument_2
          puts "Just for fun"
        end
      end
    end
    
  2. How to call rake task with arguments
    You can call

    rake "your_domain:your_task[variable_1, variable_2]"
    

Thanks for reading & enjoy coding!

Published by

Colin Dao

I am a hardworking Rubyist in Hanoi, Vietnam

Leave a comment