-1

I have a rake task that returns a count of records for a given email. The email is provided to the rake task as a command line argument, like so

rake stats:count email=me@gmail.com

But if the rake task is called without an email provided (i.e. rake stats:count), I would like helpful message to appear, like "Please provide an email"

How do I do this?

I have tried this

email = ENV['email']
if email.nil? puts "Please provide an email"
end

But it errors with NameError: undefined local variable or method email' for main:Object

stevec
  • 41,291
  • 27
  • 223
  • 311
  • Possible duplicate of [How to pass command line arguments to a rake task](https://stackoverflow.com/questions/825748/how-to-pass-command-line-arguments-to-a-rake-task) – Eyeslandic Jul 01 '19 at 14:34
  • 1
    you don't have access to that(`email`) variable/method unless you define it in your rake task. The way to access arguments depends on how you named them in your `do |_task, args|`, in this case I named it `args`, so, in your case, let's suppose you have it like `namespace :stats do`... `task :count, [:email] => :environment do |_task, args|`. So, in your rake code you'd access `email` as `args[:email]` – fanta Jul 01 '19 at 14:53
  • You can just check `if ENV['email']` then. – Eyeslandic Jul 01 '19 at 15:14
  • Works fine for me – Eyeslandic Jul 01 '19 at 15:18
  • Are you showing your whole code? – Eyeslandic Jul 01 '19 at 15:18
  • 1
    yeah, I think you need to put a little bit more of your code. Just put your task definition, add some `...` and put where you are accessing that value, then add some more `...` to hide code you don't want to show, and put the `end` to see where your rake task definition ends. – fanta Jul 01 '19 at 15:41

1 Answers1

0

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

stevec
  • 41,291
  • 27
  • 223
  • 311