Search code examples
ruby-on-railsrubyrake

I don't understand how to add arguments to a rake task. (Excerpt from the documentation)


I'm trying to create a custom rake task that takes in two arguments and uses them in my code.

I'm looking at the rails documentation and I see this excerpt for running a rails task with an argument:

task :task_name, [:arg_1] => [:pre_1, :pre_2] do |t, args|
  # You can use args from here
end

The rake task can then be invoked like this:

bin/rake "task_name[value 1]"

However, this is way too vague for me. The rails documentation fails to give a concrete example of a rake task with an argument.

For example, I'm looking at this code and I'm thinking what does bin/rake "task_name[value 1]" do? What is [:pre1, :pre2]?

Additionally, I've found some other fantastic links that do things a little bit differently. Here are the links.

Thoughtbot version

In the thoughtbot version that have this example

 task :send, [:username] => [:environment] do |t, args|
   Tweet.send(args[:username])
 end

What is the [:username => [:environment]? its different than the official rails docs.

Here is another: 4 ways to write rake tasks with arguments

I've also looked at the officail optparser documentation and that too has a different way of making it work.

All I want is for this example code that I have to work on my .rake file:

require 'optparse' 
task :add do 
  options = {}
  OptionParser.new do |opts| 
    opts.banner = "Usage: rake add" 
    opts.on("-o", "--one ARGV", Integer) { |one| options[:one] = one } 
    opts.on("-t", "--two ARGV", Integer) { |two| options[:two] = two } 
  end.parse! 
  puts options[:one].to_i + options[:two].to_i
end 

The code fails because of invalid option: -o. I just want to make this work so I can move on. Does anyone have any thoughts?


Solution

  • Here is one of my rake tasks with arguments:

    namespace :admin do
      task :create_user, [:user_email, :user_password, :is_superadmin] => :environment do |t, args|
        email = args[:email]
        password = args[:password]
        is_superadmin = args[:is_superadmin]
        ... lots of fun code ...
      end
    end
    

    and I invoke this task like this:

    rake admin:create_user['admin@example.com','password',true]
    

    EDIT

    To pass flags in you can do something like this:

    task :test_task do |t, args|
      options = {a: nil, b: nil}
      OptionParser.new do |opts|
        opts.banner = "Usage: admin:test_task [options]"
          opts.on("--a", "-A", "Adds a") do |a|
            options[:a] = true
          end   
          opts.on("--b", "-B", "Adds b") do |b|
            options[:b] = true
          end   
        end.parse!
    
      puts options.inspect
    end
    

    And examples of invoking it:

    rake admin:test_task -A -B
    rake admin:test_task -A
    rake admin:test_task -B