Search code examples
ruby-on-railsrubyrake

How to use date as parameters for a rake task


I have a rake task as below, where one needs to input the date in the import_date section in order to execute it. The date put in the import_date section then gets saved in a column called import_date in a table.

namespace :graduated_member do
  desc 'import member'
  task: create_csv, ['import_date'] => :environment do |task, args|
  #actions

Now, I want the code to only work if the right kind of date was put in. If the format was wrong, I want it to not execute the rake task, but give me an error code, telling me that the date format is wrong.

# This should work
RAILS_ENV=production ./bin/rake member:create_csv[20201119]

# This shouldn't work, because the date has too many digits.
RAILS_ENV=production ./bin/rake member:create_csv[20200001119]

Would the code below be appropriate in order to do so?

namespace :graduated_member do
  desc 'import member'
  task: create_csv, ['import_date'] => :environment do |task, args|
    require 'date'
    date = Date.today
    if args.worked_on == date.strftime("%Y%m%d")
      # action
    else
     p "ERROR"
    end
  end

Update

I don't necessarily want it the code to compare the 'import_date' to today's date, I want it to just see if the 'import_date' put in by the user follows the rule of "%Y%m%d". In this case, would the code below be better?

namespace :graduated_member do
  desc 'import member'
  task: create_csv, ['import_date'] => :environment do |task, args|
  if args.import_date.strftime("%Y%m%d")
    # action
  else
    p "ERROR"
  end

Solution

  • You can use to_date method on a string to convert args to Date object. Then you can call today? method to check the passed date. Also, you don't need to require date it's already required by Rails.

    namespace :graduated_member do
      desc 'import member'
      task :create_csv, ['import_date'] => :environment do |task, args|
        if args['import_date'].to_date.today?
          # action
        else
          p "ERROR"
        end
      end
    end
    

    In this case, if the date format is incorrect you'll get this exception ArgumentError: invalid date

    UPD

    If you want to compare with the other date.

    namespace :graduated_member do
      desc 'import member'
      task :create_csv, ['import_date'] => :environment do |task, args|
        if args['import_date'].to_date == Date.new(2020, 11, 26)
          # action
        else
          p "ERROR"
        end
      end
    end
    

    If you want to make sure that your argument is following the certain pattern

    namespace :graduated_member do
      desc 'import member'
      task :create_csv, ['import_date'] => :environment do |task, args|
        Date.strptime(args['import_date'], '%Y%m%d')
          # action
        rescue ArgumentError
          p "ERROR"
      end
    end